gpt4 book ai didi

javascript - 有没有办法将深度嵌套对象的所有值类型定义为字符串类型?

转载 作者:行者123 更新时间:2023-12-02 23:39:45 27 4
gpt4 key购买 nike

假设这个嵌套对象:

const nestedObj = {
definition: {
name: 'Mike',
prop1: {
value1: 'This is a string',
prop2: {
value2: 'String again',
},
},
},
};

有没有一种谨慎的方式来做这样的事情:

type NestedObj = {
definition: AllValuesAreOfTypeString
}

最佳答案

this您在寻找什么?

否则,通过编写您已有的确切代码,您就为 nestedObj 指定了以下类型:

{
definition: {
name: string,
prop1: {
value1: string,
prop2: {
value2: string,
},
},
},
}

例如,如果您提取嵌套属性之一:

const nestedProp = nestedObj.definition.prop1.value1;

它将被正确键入为字符串:

(nestedProp: string);

如果您尝试将深度嵌套的属性设置为不同的类型:

nestedObj.definition.prop1.value1 = 1;

您将收到类型错误:

Cannot assign 1 to nestedObj.definition.prop1.value1 because number [1] is incompatible with string [2].

您也无法在该对象上设置其他 Prop ,因为它是密封的:

nestedObj.undefinedProp = 'test';

最后,您实际上可以通过执行以下操作来保存 nestedObj 的类型:

type NestObject = typeof nestedObj;

例如,您可以在其他对象上使用此类型:

const nestedObj2: NestedObject = {
definition: {
name: 'test',
prop1: {
value1: 'value1',
prop2: {
value2: 'test',
}
},
},
};

因此,如果您以与 nestedObj1 不匹配的方式定义 nestedObj2,则会收到错误消息:


const nestedObj3: NestedObject = {
definition: {
name: 1, // Error!
// Cannot assign object literal to `nestedObj3` because
// number [1] is incompatible with string [2] in property
// `definition.name`.
prop1: {
value1: 'value1',
prop2: {
value2: 'test',
}
},
},
};

(Try Flow)

编辑:添加了第一个示例,因为我第一次可能误解了这个问题。

关于javascript - 有没有办法将深度嵌套对象的所有值类型定义为字符串类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56133457/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com