【工具】ArkTS类型助手:从json到interface声明

635 阅读2分钟

在开发ArkTS的过程中,让我感到最烦躁的事,是类型定义。在上一篇文章《Web前端浅谈ArkTS组件开发》中,我提到了从ts角度,ArkTS的在开发过程中的几处不便:

  • 类型推断几乎没有;
  • 没有type类型声明;
  • 不能一次性声明嵌套的复杂类型;
  • 没有any/unknown类型,Object有点类似unknown,仅此而已;
  • 不支持解构取值。

其中,不能一次性声明嵌套类型,最让人头疼。比如下面这个结构:

{
    "data1": {
        "data": {
            "picList": [
                {
                    "version": "111",
                    "picture": "someurl",
                }
            ],
            "time": "3333",
            "o2o": false,
            "shop": "苏宁自营",
            "info": {
                "cid": "555",
                "cName": "洗涤清洁用品",
                "pid": "777"
            },
            "type": "333",
        },
    },
    "otherData": ""
}

上面这个结构,可以使用tstype结构直接声明:

type TProduct = {
    data1: {
        data: {
            picList: {
                version: string;
                picture: string;
            }[];
            time: string;
            o2o: boolean;
            shop: string;
            info: {
                cid: string;
                cName: string;
                pid: string;
            };
            type: string;
        };
    };
    otherData?: string;
}

ArkTS中,首先不支持使用type声明类型,只能用interface;其次,每次只能声明一层类型:

interface IProduct {
    // 这样是不允许的
    data1: {
        // ...
    }
}

必须先声明data1的类型,然后在IProduct中引用:

interface IProductData1 {
    data: Object;
}
interface IProduct {
    data1: IProductData1;
    otherData?: string;
}

那么,IProductData1中的data,继续声明:

interface IProductData1Data {
    time: string;
    o2o: boolean;
    shop: string;
    type: string;
    info: Object;
    picList: Object[];
}
interface IProductData1 {
    data: IProductData1Data;
}
interface IProduct {
    data1: IProductData1;
    otherData?: string;
}

基本就是这样,一层层剥离内嵌类型。本厂商品详情的结构类型,我就这么写了1900多行。仅类型声明!1900多行!

然后进入本文主题:给大家介绍一个辅助工具,用于解决上述痛点:json2interface

image.png

就是将现有的json,按上面的步骤,一步步拆解为单层的interface,然后组装起来。

祝各位鸿蒙开发顺利!