[英]Is it possible to modify the inferred type of a literal in TypeScript?
考慮以下代碼,它嘗試有條件地將屬性添加到具有推斷類型的 object:
const foo = {
a: 1,
b: 2,
};
if (bar) {
foo.c = 3; // Error: Property 'c' does not exist on type '{ a: number; b: number; }'.(2339)
}
可以通過將foo
的類型顯式聲明為{ a: number; b: number; c?: number; }
來消除錯誤。 { a: number; b: number; c?: number; }
或使用價差有條件c
{ a: number; b: number; c?: number; }
const foo = {
a: 1,
b: 2,
...(bar ? { c: 3 } : {}),
};
但是,假設我們想保留原始代碼結構,但我們也想避免必須顯式聲明可以推斷的屬性。 有沒有可以同時滿足這兩個方面的解決方案? 例如,是否可以以某種方式調整推斷的類型,例如:
const foo = {
a: 1,
b: 2,
} as { ...; c?: number; }; // Example, does not work
這並不漂亮,但它確實有效: a
和b
的屬性類型是推斷出來的,並且不必重復聲明。
function withMissingProps<T>() {
return function<S>(obj: S): S & Partial<T> {
return obj;
}
}
const foo = withMissingProps<{ c: number }>()({
a: 1,
b: 2
});
if(Math.random() > 0.5) {
foo.c = 1;
}
聲明和推斷屬性分別有兩個類型參數T
和S
。 不幸的是,如果 function 有兩個類型參數,那么您必須同時提供或推斷兩者; 解決方案是咖喱 function,雖然這意味着額外的一對括號。
我還發現了這個 hack,不幸的是它編譯為Object.assign
,因此運行時成本不為零:
const foo = {
a: 1,
b: 2,
...{} as {
c?: number,
},
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.