我试图通过使用Array.prototype.filter从数组中过滤null(undefined)元素,但TypeScript编译器似乎无法识别"过滤器"函数的派生数组并且未能通过类型检查.
假设遵循简化代码,其中我有一个带有(number | undefined)[]类型的数组,并希望过滤undefined以适合number []数组.
const arry = [1, 2, 3, 4, "5", 6];
const numArry: number[] = arry
.map((i) => {
return typeof i === "number" ? i : void 0;
})
.filter((i) => i);
Run Code Online (Sandbox Code Playgroud)
错误说:
类型'(number | undefined)[]'不能分配给'number []'.输入'号码| undefined'不能分配给'number'类型.类型'undefined'不能分配给'number'类型.
我可以将结果数组转换为数字[],如下所示,知道过滤器函数删除undefined.
const arry = [1, 2, 3, 4, "5", 6];
const numArry: number[] = (arry
.map((i) => {
return typeof i === "number" ? i : void 0;
})
.filter((i) => i) as Number[]);
Run Code Online (Sandbox Code Playgroud)
除了铸造之外,还有更好的方法来实现这一目标吗?
环境:TSC2.1启用了strictNullChecks.
使用时Array.filter()我不确定如何实现我在下面描述的内容。
我不想为此创建一个新类型(但如果没有其他办法,那也没关系):
interface GPSLocation {
lat: number
lng: number
}
interface House {
address: string
location?: GPSLocation
}
const house01: House = {
address: '123 street'
}
const house02: House = {
address: '123 street',
location: {
lat: 111.111,
lng: 222.222
}
}
const allHouses = [house01, house02]
// Infered by Typescript: const gpsLocationList: (GPSLocation | undefined)[]
// Expected: const gpsLocationList: (GPSLocation)[]
const gpsLocationList = allHouses.filter((house) => house.location !== undefined).map(house => house.location)
Run Code Online (Sandbox Code Playgroud) typescript ×2