代码如下(TS Playground here):
interface IConversionData {
[index: string]: IConversionData | string;
}
const conversionData: IConversionData = { header: {}}
conversionData.header["9106"] = "4";
conversionData.header["9132"] = "1";
conversionData.header.myChild2["abc"] = "1"; //Property 'myChild2' does not exist on type 'string | IConversionData'. Property 'myChild2' does not exist on type 'string'.
我知道recursive interface types are possible in TypeScript但这仍然会引发错误。为什么呢?
答案 0 :(得分:3)
它与递归无关:
(conversionData.header) is of type IConversionData | string
因此,它告诉您无法访问myChild2
,因为其中一个选项是string
且string
缺少myChild2
。
顺便说一下,通过执行以下操作可以轻松修复您的示例:
export interface IConversionData {
[index: string]: IConversionData | string;
}
const conversionData: IConversionData = { header: {}}
conversionData.header["9106"] = "4";
conversionData.header["9132"] = "1";
conversionData.header["myChild2"] = {abc: "1"};