问题描述
我在 TypeScript 中有以下接口:
I have the following interface in TypeScript:
interface IX {
a: string,
b: any,
c: AnotherType
}
我声明了一个该类型的变量并初始化了所有属性
I declare a variable of that type and I initialize all the properties
let x: IX = {
a: 'abc',
b: null,
c: null
}
然后我稍后在 init 函数中为它们分配实际值
Then I assign real values to them in an init function later
x.a = 'xyz'
x.b = 123
x.c = new AnotherType()
但我不喜欢在声明对象时必须为每个属性指定一堆默认的空值,因为它们稍后将被设置为实际值.我可以告诉界面将我不提供的属性默认为 null 吗?什么会让我这样做:
But I don't like having to specify a bunch of default null values for each property when declaring the object when they're going to just be set later to real values. Can I tell the interface to default the properties I don't supply to null? What would let me do this:
let x: IX = {
a: 'abc'
}
没有得到编译器错误.现在它告诉我
without getting a compiler error. Right now it tells me
TS2322:类型{}"不可分配给类型'九'.类型{}"中缺少属性b".
推荐答案
没有.你不能为接口或类型别名提供默认值,因为它们只是编译时,默认值需要运行时支持
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()
这篇关于Typescript 接口默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!