const data = {
code:'948',
'湖南省':{
code:'32',
'长沙市':{
code:'88',
'雨花区':{
code:'9827'
}
}
},
'新疆':{
code:'66',
'乌鲁木齐市':{
code:'65',
'头屯河区':{
code:'870'
}
}
}
}
该如何声明这个data的类型呢。
我之前尝试过如下:
interface DataType {
code: string // 这里code会报错,和string和DataType类型不兼容
[key:string]: DataType
}
后来改成:
interface DataType {
code: string
[key:string]: DataType | string
}
但这样子当访问data['a'].code的时候就会报错,因为 string | DataType 没有code属性。
我觉得是因为code也是string,所以希望在DataType中的第二行的string里去掉'code'这个字符串。于是我写成:
interface DataType {
code: string
[key: Exclude<string, 'code'>]: DataType
}
结果这样也不行。
所以到底怎么声明这样一个类型呢,要求一个对象必须有一个键为code,值类型为字符串,其他键为字符串,值为该对象本身的类型。
求教,谢谢各位大佬。
传送门:TypeScript: TS Playground