返回
TypeScript踩坑系列:初识类型系统之Property ‘xx’ does not exist on type ‘Function’
前端
2023-11-25 23:16:38
初探Typescript类型系统
Typescript是一种强类型语言,具有静态类型系统,这意味着在编译时就会检查类型。类型系统可以帮助我们尽早发现错误,提高代码质量。
在Typescript 中,每个变量都有一个类型。类型可以是基本类型,例如number、string和boolean,也可以是复杂类型,例如数组、对象和函数。
函数类型是指函数的类型。函数类型的语法如下:
(参数类型列表) => 返回值类型
例如,以下代码定义了一个函数类型,该函数接受两个数字作为参数,并返回一个数字:
(number, number) => number
Property ‘xx’ does not exist on type ‘Function’ 错误的原因
在Javascript中获取对象的属性或者方法使用点或者中括号的这两种方式即可,例如:
const obj = {
name: '张三',
age: 20
}
console.log(obj.name) // 输出: 张三
console.log(obj['age']) // 输出: 20
但是在Typescript 中,有时会提示像Property'value'doesnotexistontype'Ob这样的错误。这是因为 Typescript 编译器在编译时会检查类型,如果它发现某个属性不存在于对象的类型中,就会抛出这个错误。
例如,以下代码会报错:
class Person {
name: string;
}
const person = new Person();
console.log(person.age); // 报错: Property 'age' does not exist on type 'Person'.
因为 Person 类的类型中没有 age 属性,所以在编译时就会报错。
解决方法
为了解决这个问题,我们可以显式地为 Person 类添加 age 属性:
class Person {
name: string;
age: number;
}
const person = new Person();
person.age = 20;
console.log(person.age); // 输出: 20
现在,代码就可以正常运行了。
总结
Property ‘xx’ does not exist on type ‘Function’ 这个错误通常是因为 Typescript 编译器在编译时发现某个属性不存在于对象的类型中。要解决这个问题,我们可以显式地为对象添加该属性。