TypeScript可选属性与方法

TypeScript可选属性与方法,在默认情况下,接口中属性签名和方法签名定义的对象属性都是必选的。在给接口类型赋值时,如果未指定必选属性则会产生编译错误。

interface Foo {
   x: string;
   y(): number;
}

const a: Foo = { x: 'hi' };
//    ~
//    编译错误!缺少属性 'y'

const b: Foo = { y() { return 0; } };
//    ~
//    编译错误!缺少属性 'x'

// 正确
const c: Foo = {
   x: 'hi',
   y() { return 0; }
};

我们可以在属性名或方法名后添加一个问号“?”从而将该属性或方法定义为可选的。可选属性签名和可选方法签名的语法如下所示:

PropertyName?: Type

PropertyName?(ParameterList): Type

下例中,接口Foo的属性x和方法y都是可选的:

interface Foo {
   x?: string;
   y?(): number;
}

const a: Foo = {}
const b: Foo = { x: 'hi' }
const c: Foo = { y() { return 0; } }
const d: Foo = { x: 'hi', y() { return 0; } }

如果接口中定义了重载方法,那么所有重载方法签名必须同时为必选的或者可选的。示例如下:

// 正确
interface Foo {
   a(): void;
   a(x: boolean): boolean;

   b?(): void;
   b?(x: boolean): boolean;
}

interface Bar {
   a(): void;
   a?(x: boolean): boolean;
//  ~
//  编译错误:重载签名必须全部为必选的或可选的
}

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!