Roc*_* Li 43 types type-alias typescript
Typescript 类型别名可以支持默认参数吗?例如:
export type SomeType = {
typename: string;
strength: number;
radius: number;
some_func: Function;
some_other_stat: number = 8; // <-- This doesn't work
}
Run Code Online (Sandbox Code Playgroud)
错误是A type literal property cannot have an initializer.
我找不到与此相关的文档 -type关键字在也称为类型的其他所有内容后面非常模糊。我可以做些什么来type在打字稿中设置默认参数值吗?
小智 44
您不能将默认值直接添加到类型声明中。
你可以这样做:
// Declare the type
export type SomeType = {
typename: string;
strength: number;
radius: number;
some_func: Function;
some_other_stat: number;
}
// Create an object with all the necessary defaults
const defaultSomeType = {
some_other_stat: 8
}
// Inject default values into your variable using spread operator.
const someTypeVariable: SomeType = {
...defaultSomeType,
typename: 'name',
strength: 5,
radius: 2,
some_func: () => {}
}
Run Code Online (Sandbox Code Playgroud)