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});


typescript学习15

可以看到,传入的参数里面x, y都是可选的,如果没有这些参数,x, y属性就认为是undefined。

但是同时你也不能直接去访问x和y的值。

比如这样使用:

function paintShape(opts: PaintOptions) {
    let x: number = opts.x;
    let y: number = opts.y;
}

编译器就能检测到错误。


typescript学习15

这时候就需要对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;
}
展开阅读全文

页面更新:2024-04-29

标签:编译器   写法   别名   繁琐   属性   定义   对象   参数   类型   方式

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top