【问题标题】:Default value for typescript type aliastypescript 类型别名的默认值
【发布时间】:2020-09-03 19:36:46
【问题描述】:

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

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 设置默认参数值吗?

【问题讨论】:

    标签: typescript types type-alias


    【解决方案1】:

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

    你可以这样做:

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

    【讨论】:

    • someTypeVariable被注入到一个函数中时,你是怎么做的呢?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      相关资源
      最近更新 更多