【发布时间】:2022-01-08 10:42:08
【问题描述】:
我想写一个 typeguard 来检查数组的所有子元素是否都是 T 类型,从而使它成为一个 T 是泛型类型的数组
// Assume arr of any type but Array
const arr: any[] = [
{
foo: "bleh1",
bar: 1
},
{
foo: "bleh2",
bar: 2
},
]
interface newType {
foo: string
bar: number
}
// Check that arr is an array of newType , ie arr: newType[]
const isArrayOf = <T,>(arr: any): arr is Array<T> => {
// TypeScript mastery needed here
return true
}
if(isArrayOf<newType>(arr)){
arr
}
【问题讨论】:
-
从 GitHub Copilot 获得建议,但无法理解第二个参数
typescript const isArrayOf = <T>(arr: any[], type: new (...args: any[]) => T): arr is T[] => { return arr.every((item) => item instanceof type) } -
类型系统在运行时不存在。您无法检查某些内容是否符合泛型类型,因为函数运行时没有“geneics”或“types”。
-
建议使用具体类型并传入一个类。但是,当类型是接口时,这是不可能的。
-
我认为它可能像描述的 [here] (2ality.com/2020/06/…) 但我无法理解它的工作原理,因此想对函数参数进行一些解释
-
同样,如果您有 具体类型,这将有效。运行时存在的东西。一类。如果您有一个接口,则不会 - 仅在编译时存在。
标签: arrays typescript typeguards generic-type-parameters