gpt4 book ai didi

javascript - typescript 动态检查字符串是否是复杂对象的属性

转载 作者:行者123 更新时间:2023-11-30 20:33:02 25 4
gpt4 key购买 nike

我真的需要能够动态检查 aa 是否是我称为验证的复杂对象的属性

const check = 'propertya' + 'a'; // result of a complex calculation that returns string 'propertyaa'

validations= {
'a' : {
'propertyaa': 'ax',
'ab': 'ay',
'ac': 'az'
},
'b' : {
'ba': 'ax',
'bb': 'ay',
'bc': 'az'
}
};

if (this.validations.a[check] === undefined) { ...

错误是:

element implicitly has an any type because type '{ ' propertyaa': string, 'ab': string, 'ac': string; }' has no index signature
(property) 'a': {
'propertyaa': string;
'ab': string;
'ac': string;
}

奇怪的是,静态(非动态)变体有效 if (this.validations.a['ab']) {

最佳答案

您可以选择两条路线之一。您可以将索引签名添加到您的验证属性:

type Indexable = { [name: string]: string }
const validations = {
'a': {
'propertyaa': 'ax',
'ab': 'ay',
'ac': 'az'
} as Indexable,
'b': {
'ba': 'ax',
'bb': 'ay',
'bc': 'az'
} as Indexable
};

const check = 'propertya' + 'a';
if (validations.a[check] === undefined) {
}

您也可以在使用时将该属性转换为 Indexable:

if ((validations.a as Indexable)[check] === undefined) {
}

你也可以使用 any 而不是 Indexable,但是上面定义的 Indexable 提供了比 any 更多的类型安全>

另一种选择是断言字符串 check 实际上是 a 值的键:

if (validations.a[check as 'propertyaa'] === undefined) {
}

编辑

如果您选择第一个选项,辅助函数可以帮助避免对 validations 的每个属性进行类型断言的需要:

type Indexable = { [name: string]: string }
const validations = createValidations({
'a': {
'propertyaa': 'ax',
'ab': '19',
'ac': 'az'
},
'b': {
'ba': 'ax',
'bb': 'ay',
'bc': 'az'
}
});
function createValidations<T>(o: { [P in keyof T]: T[P] & Indexable}) : typeof o {
return o;
}
const check = 'propertya' + 'a';
if (validations.a[check] === undefined) {
}

关于javascript - typescript 动态检查字符串是否是复杂对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50137087/

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