[英]TypeScript generic array type predicate
我想要一個通用類型謂詞,它允許我檢查對象屬性的類型。
為了說明這一點,我想實現以下目標:
const a: { [key in string]: string | string[]} = {
arrayProp: ["this", "is", "an", "array"],
otherProp: "this is a string"
};
Object.keys(a).forEach((prop: keyof typeof a) => {
if (isArrayProperty(a, prop)) {
// `a[prop]` is correctly detected as array
a[prop].push("another value")
}
})
我期待這樣的事情能奏效
function isArrayProperty<T, P extends keyof T>(
obj: T,
prop: P,
): T[P] is Array<any> {
return Array.isArray(obj[prop]);
}
但是 TypeScript 似乎與 generics 有問題並且is
返回類型中的語句。
我知道我可以將值傳遞給 function,例如Array.isArray(a["arrayProp"])
以使其工作。 但是,我想 go 更進一步,我傳入一個構造函數和一個屬性,以查看 object 的屬性是否為數組類型:
type ClassConstr<T> = new (...props) => T
function isArrayProperty<T, P extends keyof T>(
obj: ClassConstr<T>,
prop: P,
): T[P] is Array<any> {
return // some magic happening here;
}
class A {
someProp: any;
}
const a = new A()
a = ["some", "array"];
if (isArrayProperty(A, "someProp") {
// `a.someProp` is correctly detected as array
a.someProp.push("new value");
}
背景是,我的類有一個單獨的模式定義,僅在運行時可用。 這些模式定義然后決定屬性是否是數組、字符串、日期……因此,我希望有一個 function 允許我在使用這些類的組件中仍然實現類型安全。
考慮一下:
const a: { [key in string]: string | string[] } = {
arrayProp: ["this", "is", "an", "array"],
otherProp: "this is a string"
};
function isArrayProperty<T, P extends keyof T>(
obj: T,
prop: P,
): obj is T & Record<P, Array<any>> {
return Array.isArray(obj[prop]);
}
Object.keys(a).forEach((prop: keyof typeof a) => {
if (isArrayProperty(a, prop)) {
a[prop].push("another value")
}
})
您需要向 TS 保證isArrayProperty
中的obj
是一個具有 prop P
和值Array<any>
的記錄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.