[英]Typescript: type guard for whether an object property is defined, when the key is a wide type?
我有一個返回對象屬性是否為undefined
的函數。 我需要這個函數而不是僅僅做obj[key] === undefined
因為否則我有時會得到Property 'foo' does not exist on type 'Bar'.
. 當屬性鍵是文字時,編寫類型很簡單。 IE:
function hasDefinedProp<
Obj extends Partial<Record<string, any>>,
Prop extends string,
>(
obj: Obj,
prop: Prop,
): obj is Obj & Record<Prop, Prop extends keyof Obj ? Exclude<Obj[Prop], undefined> : unknown> {
return obj[prop] !== undefined;
}
const obj: Partial<Record<string, number>> = {};
if (hasDefinedProp(obj, 'foo')) {
obj.foo + 1; // No error.
obj.bar + 1; // "Object is possibly 'undefined'."
}
但是,當鍵的類型是寬類型時,這不起作用,即:
const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
obj[key] + 1; // No error.
obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}
是否可以使類型保護適用於寬類型?
AFAIK,這是不可能的。 將顯式
string<\/code>類型添加到
const key: string = '';<\/code>
-TS 無法縮小
key<\/code>的文字類型。
因此,您可以使用任何想要訪問屬性的字符串。
在這個例子中,TS 無法區分兩種類型為
string<\/code>的類型:
const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
obj[key] + 1; // No error.
obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.