且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Typescript 接口默认值

更新时间:2022-12-05 10:56:16

我可以告诉接口将我不提供的属性默认为 null 吗?什么会让我这样做

Can I tell the interface to default the properties I don't supply to null? What would let me do this

没有.你不能为接口或类型别名提供默认值,因为它们只是编译时,默认值需要运行时支持

No. You cannot provide default values for interfaces or type aliases as they are compile time only and default values need runtime support

但未指定的值在 JavaScript 运行时默认为 undefined.所以你可以将它们标记为可选:

But values that are not specified default to undefined in JavaScript runtimes. So you can mark them as optional:

interface IX {
  a: string,
  b?: any,
  c?: AnotherType
}

现在当你创建它时你只需要提供a:

And now when you create it you only need to provide a:

let x: IX = {
    a: 'abc'
};

您可以根据需要提供值:

You can provide the values as needed:

x.a = 'xyz'
x.b = 123
x.c = new AnotherType()