简体   繁体   English

类型'T'上不存在属性 - 一般问题

[英]Property does not exist on type 'T' - Generic problems

I have a util that takes an array and a predicate to perform a filtration of the array, however after using my custom type for the predicate I am getting an error stating 我有一个util,它接受一个数组和一个谓词来执行数组的过滤,但是在使用我的自定义类型作为谓词后,我收到一个错误说明

property 'name' does not exist on type 'T' 类型'T'上不存在属性'name'

I thought that the generic property type T would have accepted anything? 我认为通用属性类型T会接受任何东西吗?

Am I missing something obvious? 我错过了一些明显的东西吗

Array.ts Array.ts

export type arrayPredicate = <T>(arg: T) => boolean;

ArrayUtil ArrayUtil

static filterArray<T>(array: T[], arrayPred: arrayPredicate): T {
    const key =  Object.keys(array).find(obj => arrayPred(array[obj]));
    return array[key];
  }

Usage in test 用于测试

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));

  ...

});

Of course, changing 当然,改变

Change your arrayPredicate declaration as shown below. 更改您的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];
  }
}

Since you are not declaring parameter in type for arrayPredicate, it is assumed to be empty object. 由于您没有为arrayPredicate声明类型中的参数,因此假定它是空对象。

Here is working example, 这是工作的例子,

TypeScript example TypeScript示例

Need to add a type for your array for exmaple lets sat type of the array is SampleType[] . 需要为SampleType[]添加数组类型,让数组的sat类型为SampleType[] Then is should be 那应该是

const array: SampleType[] = [
  {
    'name': 'object-1',
    'id': 1
  },
  {
    'name': 'object-2',
    'id': 2
  }
];

Then pass that type to the generic function 然后将该类型传递给泛型函数

 ArrayUtils.filterArray<SampleType>(exceptionalStatuses, (status: SampleType => status.name === findStatus));

SampleType should be SampleType应该是

export class SampleType{
  name: string,
  id: string
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM