打字稿类型别名的默认值

Default value for typescript type alias

typescript类型别名可以支持默认参数吗?例如:

export type SomeType = {
    typename: string;
    strength: number;
    radius: number;
    some_func: Function;
    some_other_stat: number = 8; // <-- This doesn't work
}

错误是A type literal property cannot have an initializer.

我找不到与此相关的文档 - type 关键字在其他所有也命名为类型的东西后面非常模糊。我能做些什么来在打字稿中为 type 设置默认参数值吗?

您不能将默认值直接添加到类型声明中。

您可以改为这样做:

// 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: () => {}
}

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