在TypeScript中,函数Array.Prototype.includes要求我传递与原始数组相同的类型。但是我在想,使用includes来找出一个任意string类型的键是否存在于一个已知类型的数组中,这不是整个意义所在吗?
请考虑以下代码:
type CONFIG_MODEL = {
URL: string;
Protocol: string;
Port: number;
Encrypted: boolean;
}
const ALLOWED_KEYS: (keyof CONFIG_MODEL)[] = ['URL', 'Protocol'];
function setup(configs: { [key: string]: string }) {
Object.keys(configs).forEach(configKey => {
if (ALLOWED_KEYS.includes(configKey)) {
// do something
}
})
}TypeScript在使用includes时抛出一个错误,声明:
“string”类型的参数不能分配给“CONFIG_MODEL的键”类型的参数
谢谢!
发布于 2021-04-21 07:03:55
只需尝试迭代允许的键,而不是整个对象键示例:
type CONFIG_MODEL = {
URL: string;
Protocol: string;
Port: number;
Encrypted: boolean;
}
type AllowedKeys = Array<keyof CONFIG_MODEL>;
const ALLOWED_KEYS: AllowedKeys = ['URL', 'Protocol'];
const hasProperty=<Obj,Prop extends string>(obj:Obj,prop:Prop):obj is Obj & Record<Prop,string>=>
Object.prototype.hasOwnProperty.call(obj,prop);
function setup(configs: { [key: string]: string }) {
ALLOWED_KEYS.forEach(elem=>{
if(hasProperty(configs, elem)){
// do smth with config
const result = configs[elem] // ok
}
})
}发布于 2022-11-10 16:24:23
这里倒数第二个行中的as string[]强制转换(就在.includes之前)也解决了这个问题:
//type externally defined in original
type ClassicalElement = 'earth' | 'water' | 'wind' | 'fire';
const classicalElements = ['earth', 'water', 'wind', 'fire'] as ClassicalElement[];
const isClassicalElement = function(
possibleElement: string
): possibleElement is ClassicalElement {
return (classicalElements as string[]).includes(possibleElement);
}https://stackoverflow.com/questions/67190764
复制相似问题