phy*_*boy 7 javascript types typescript angular
我有一个使用数组和谓词来执行数组过滤的实用程序,但是在将我的自定义类型用于谓词后,我收到一条错误消息
类型“T”上不存在属性“名称”
我认为通用属性类型T会接受任何东西?
我错过了一些明显的东西吗?
数组.ts
export type arrayPredicate = <T>(arg: T) => boolean;
Run Code Online (Sandbox Code Playgroud)
数组实用程序
static filterArray<T>(array: T[], arrayPred: arrayPredicate): T {
const key = Object.keys(array).find(obj => arrayPred(array[obj]));
return array[key];
}
Run Code Online (Sandbox Code Playgroud)
测试中的使用
const array = [
{
'name': 'object-1',
'id': 1
},
{
'name': 'object-2',
'id': 2
}
];
it(... , () => {
// I get red squigglies under '.name'
const myObj = ArrayUtils.filterArray(exceptionalStatuses,
(status => status.name === findStatus));
...
});
Run Code Online (Sandbox Code Playgroud)
当然,改变
更改您的 arrayPredicate 声明,如下所示。
export type arrayPredicate<T> = (arg: T) => boolean;
class ArrayUtils {
static filterArray<T>(array: T[], arrayPred: arrayPredicate<T>): T {
const key = Object.keys(array).find(obj => arrayPred(array[obj]));
return array[key];
}
}
Run Code Online (Sandbox Code Playgroud)
由于您没有在 arrayPredicate 的类型中声明参数,因此假定它是空对象。
这是工作示例,
| 归档时间: |
|
| 查看次数: |
9871 次 |
| 最近记录: |