【问题标题】:Typescript - typing array methodsTypescript - 输入数组方法
【发布时间】:2021-08-03 17:29:47
【问题描述】:

我在输入数组方法时遇到问题

 const person = students.findIndex((student) => student.id === 23)

我得到的第一个错误是括号中的学生元素

 const person = students.findIndex((student) => student.id === 23)

TS7006:参数“student”隐含的类型为“any”。

这可以解决

 const person = students.findIndex((student:any) => student.id === 23)

这不是很好,所以我尝试

 const person = students.findIndex((student:Object) => student.id === 23)

但我明白了

TS2339:“对象”类型上不存在属性“id”

我假设是因为 Object 是通用类型。

这里的最佳做法是什么?我用 filter、map、reduce 做了数百个这样的操作,我必须在 typescript 中定义方法处理的元素吗?

【问题讨论】:

  • 你的students数组有类型吗?
  • 创建存储在学生数组中的接口Student

标签: javascript arrays typescript filter


【解决方案1】:

创建Student 接口并提供相同的接口来代替Object 和任何其他地方进行类型检查。我建议明确提及类型(良好的编码习惯),即使 TS 可以进行隐式类型检查。

interface Student {
  id: number;
  name: string;
  // other properties...
}

const students: Student[] = [{
  id: 123,
  name: "test123"
},
{
  id: 456,
  name: "test456"
}]; // Suppose this is the data example

const person = students.findIndex((student: Student) => student.id === 23)

【讨论】:

  • 虽然这行得通,但在语法上.. 这在语义上是不正确的。面向对象编程中的接口用于声明一个类应该实现的抽象方法列表。在这种情况下,Student 不是一个类。所以使用接口在语义上是不正确的。这就是 TS 引入类型概念的原因
  • 你怎么知道Student 不是上面问题中没有提到的类。即使您认为它是Type,并且假设某事是不正确的。通常这在大多数情况下都是类,因为学生是一个对象。
  • 是的,这正是它必须被假定为类型的原因。不要将 JS 中的 Object 与 OO 对象混淆。
  • 不要把它和OO对象联系起来,我们在JS中有类和接口的特性。所以Studentinterface描述了数据属性,可以被其他interface等扩展。
  • 就像我之前说的,没有方法可以在你的界面中实现。它仅列出对象的属性名称。这不是接口的用途...... JS没有接口的概念,它提供了极端的动态能力,如果你不正确地使用鸭子打字会很头疼。 TS 接口和类型就是为了解决这些问题而设计的。为了简单起见,如果你的接口没有方法,请使用 type
【解决方案2】:

最好使用 TypeScript 的隐式类型。

创建类型

type Student = {
  name: string;
};

const students: Student[] = [
  { name: 'ABC' },
  { name: 'DEF' }
];

const person = students.findIndex( student => student.name === 'ABC' ); // 0

当您将 students 变量声明为 Student 类型的数组时,您的数组原型将扩展自身以包含 Student 类型。因此,只要您在学生数组上调用这些方法,您的数组原型方法就会将 Student 视为它们的类型。

【讨论】:

    猜你喜欢
    • 2021-03-20
    • 2021-10-10
    • 2023-03-04
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2014-03-08
    相关资源
    最近更新 更多