有人可以解釋為什么在下面的示例代碼中打字稿給出錯誤訊息“const key: string Argument of type 'string' is notassignable to parameter of type'keyof Condition”
interface Condition {
GOOD: 'GOOD';
BAD: 'BAD';
NONE: 'NONE';
}
const ObjWithAllCondition: Condition = {
GOOD: 'GOOD',
BAD: 'BAD',
NONE: 'NONE',
};
interface Result {
condition: keyof Condition;
count: number;
}
const getKeyValue = <T extends Condition, K extends keyof T>(obj: T, key: K) => obj[key];
const getResult = (): Result[] => {
const result = [];
for (const key in ObjWithAllCondition) {
result.push({
condition: getKeyValue(ObjWithAllCondition, key), // this is error
count: 1,
});
}
return result;
};
uj5u.com熱心網友回復:
因為 TypeScript 使用結構型別系統,所以所有物件都可以具有超出其定義型別的額外屬性(只要已知的屬性可分配給物件的型別,編譯器就可以接受)。
因此,使用迭代物件鍵的in運算子或方法可能會回傳不是您期望的型別的值,因此所有這些鍵/屬性都是型別string(為了型別安全)。
您可以重構示例以Condition從可能的鍵陣列中派生型別中的屬性,然后在迭代鍵時使用該陣列。這是一個例子:
TS游樂場
const conditions = ['GOOD', 'BAD', 'NONE'] as const;
type ConditionName = typeof conditions[number];
type StringUnionToKV<S extends string> = { [K in S]: K };
type Condition = StringUnionToKV<ConditionName>;
const obj: Condition = {
GOOD: 'GOOD',
BAD: 'BAD',
NONE: 'NONE',
};
type Result = {
condition: ConditionName;
count: number;
};
const getKeyValue = <T extends Condition, K extends keyof T>(obj: T, key: K) => obj[key];
const getResult = (): Result[] => {
const result = [];
for (const key of conditions) {
result.push({
condition: getKeyValue(obj, key),
count: 1,
});
}
return result;
};
如果您要使用一組固定的字串,您可能還會對字串列舉感興趣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/429988.html
標籤:打字稿
