typescript学习15
对象类型
JavaScript里面使用对象来传递数据,TypeScript里面称这个为对象类型。
对象类型可以使用三种方式来定义:
1. 匿名方式
2. interface类型
3. 别名方式
匿名方式:function greet(person: { firstName: string, lastName: string}) { console.log("Hello, " + person.lastName + " " + person.firstName + "!"); } greet({ firstName: "San", lastName: "Zhang"});
接口方式:interface Person { firstName: string, lastName: string; } function greet(person: Person) { console.log("Hello, " + person.lastName + " " + person.firstName + "!"); } greet({ firstName: "San", lastName: "Zhang"});
别名方式:type Person = { firstName: string, lastName: string; } function greet(person: Person) { console.log("Hello, " + person.lastName + " " + person.firstName + "!"); } greet({ firstName: "San", lastName: "Zhang"}); 属性表述符(Property Modifier)可选属性
通过添加问号,定义属性为可选属性。interface PaintOptions { shape: string; x?: number; y?: number; }; function paintShape(opts: PaintOptions) { } paintShape({shape: "shape1"}); paintShape({shape: "shape2", x: 5}); paintShape({shape: "shape3", x: 5, y: 6});
可以看到,传入的参数里面x, y都是可选的,如果没有这些参数,x, y属性就认为是undefined。
但是同时你也不能直接去访问x和y的值。
比如这样使用:function paintShape(opts: PaintOptions) { let x: number = opts.x; let y: number = opts.y; }
编译器就能检测到错误。
这时候就需要对undefined进行判断。function paintShape(opts: PaintOptions) { let x: number = opts.x === undefined ? 0: opts.x; let y: number = opts.y === undefined ? 0: opts.y; }
这个写法有点繁琐,通过参数拆分(Destructuring),可以给这两个值设置默认值。function paintShape({shape, x = 0, y = 0}: PaintOptions) { let xx: number = x; let yy: number = y; }