functiongetLength(something: string | number): number { return something.length; }
// index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'. // Property 'length' does not exist on type 'number'.
上例中,length 不是 string 和 number 的共有属性,所以会报错。
对象的类型——接口
赋值的时候,变量的形状必须和接口的形状保持一致:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
interfacePerson { name: string; age: number; }
lettom: Person = { name: 'Tom' }; // index.ts(6,5): error TS2322: Type '{ name: string; }' is not assignable to type 'Person'. // Property 'age' is missing in type '{ name: string; }'.
lettom: Person = { name: 'Tom', age: 25, gender: 'male' }; // index.ts(9,5): error TS2322: Type '{ name: string; age: number; gender: string; }' is not assignable to type 'Person'. // Object literal may only specify known properties, and 'gender' does not exist in type 'Person'.
// index.ts(3,5): error TS2411: Property 'age' of type 'number' is not assignable to string index type 'string'. // index.ts(7,5): error TS2322: Type '{ [x: string]: string | number; name: string; age: number; gender: string; }' is not assignable to type 'Person'. // Index signatures are incompatible. // Type 'string | number' is not assignable to type 'string'. // Type 'number' is not assignable to type 'string'.
上例中,任意属性的值允许是 string,但是可选属性 age 的值却是 number,number 不是 string 的子属性,所以报错了。
只读属性用 readonly 表示:
1 2 3 4 5 6 7 8
interfacePerson { readonlyid: number; } lettom: Person = { id: 89757, }; tom.id = 9527; // index.ts(14,5): error TS2540: Cannot assign to 'id' because it is a constant or a read-only property.
functiontoBoolean(something: string | number): boolean { return <boolean>something; } // index.ts(2,10): error TS2352: Type 'string | number' cannot be converted to type 'boolean'. // Type 'number' is not comparable to type 'boolean'.
// index.ts(4,14): error TS2345: Argument of type 'boolean' is not assignable to parameter of type 'string | number'. // Type 'boolean' is not assignable to type 'number'.
类
使用 static 修饰符修饰的方法称为静态方法,它们不需要实例化,而是直接通过类来调用:
1 2 3 4 5 6 7 8
classAnimal { staticisAnimal(a) { return a instanceofAnimal; } } let a = newAnimal('Jack'); Animal.isAnimal(a); // true a.isAnimal(a); // TypeError: a.isAnimal is not a function