Typescript 类型别名的默认值

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)

  • 当将“someTypeVariable”注入到函数中时,如何做到这一点? (3认同)

HTN*_*HTN 18

类型在运行时不存在,因此默认值没有意义。如果你想有一个默认值,你必须使用运行时存在的东西,比如类或工厂函数