let tom: Person = { name: 'Tom', age: 25, gender: 'male' };
// 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 的子属性,所以报错了。
let tom: Person = { name: 'Tom', gender: 'male' };
tom.id = 89757;
// index.ts(8,5): error TS2322: Type '{ name: string; gender: string; }' is not assignable to type 'Person'. // Property 'id' is missing in type '{ name: string; gender: string; }'. // index.ts(13,5): error TS2540: Cannot assign to 'id' because it is a constant or a read-only property.
上例中,报错信息有两处,第一处是在对 tom 进行赋值的时候,没有给 id 赋值。
第二处是在给 tom.id 赋值的时候,由于它是只读属性,所以报错了。
数组的类型
在 TypeScript 中,数组类型有多种定义方式,比较灵活。
「类型 + 方括号」表示法
最简单的方法是使用「类型 + 方括号」来表示数组:
1
let fibonacci: number[] = [1, 1, 2, 3, 5];
数组的项中不允许出现其他的类型:
1 2 3 4 5
let fibonacci: number[] = [1, '1', 2, 3, 5];
// index.ts(1,5): error TS2322: Type '(number | string)[]' is not assignable to type 'number[]'. // Type 'number | string' is not assignable to type 'number'. // Type 'string' is not assignable to type 'number'.