1
的following code:混亂周圍打字稿類型`in`操作者
// This makes sense
type simpleKeys = 'a' | 'b';
let anObject: {
[index in simpleKeys]: string;
} = {a: 'a', b: 'b'};
anObject.a; // 'a'
// This doesn't make sense, how does `T` have many types? It is only
// a subtype of type `string`... or is the act of invoking the function
// with many strings allowing the compiler to infer that `T` is of
// type "AA" | "BB"?
function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
return o.reduce((res, key) => {
res[key] = key;
return res;
}, Object.create(null));
}
const LABELS = strEnum(['AA', 'BB']);
type LABEL = keyof typeof LABELS;
我明白T
是string
亞型所以我期待的類型系統,以超過o
其成員是陣列以某種方式遍歷T
s。就像[K in o]: K;
,但我知道這對於編譯時靜態分析沒有意義。任何人都可以指點我的資源,以瞭解如何「更好地思考類型」好一點嗎?謝謝。