【问题标题】:Type 'Type1 | Type2' is not asignable to type 'Type1'输入'Type1 | Type2' 不可分配给类型 'Type 1'
【发布时间】:2018-09-25 19:16:11
【问题描述】:

你好,我有这些类型的定义

export interface ICubeParams{
  width:number,
  depth:number,
  height:number,
  color?:string
}

export interface ISphereParams{
  radius:number
  color?:string
}

和一个变量类型:

let parameters: ICubeParams | ISphereParams

然后,在另一个类 Cube 中,我将参数传递给构造函数(在这种情况下,参数是 ICubeParams 类型)

const params: ICubeParams = this.parameters;

但我收到以下错误

Type 'ICubeParams | ISphereParams' is not assignable to type 'ICubeParams'.

任何线索我做错了什么?

【问题讨论】:

  • params 必须是 ICubeParamsparameters 可能是别的东西,这就是它不匹配的原因

标签: typescript typescript-typings


【解决方案1】:

parameters 可以是ICubeParamsISphereParams。当您将其分配给必须为 ICubeParams 类型的 params 时,打字稿编译器会抱怨它无法验证分配是否有效。也许parametersISphereParams,而您将其分配给params

如果您确定在分配发生时parameters 不会是ISphereParams,则可以使用类型断言:

const params = this.parameters as ICubeParams ;

或者您可以使用类型保护来确保分配有效(并让 typescript 知道您执行了检查的事实):

let parameters: ICubeParams | ISphereParams

//in type guard
if ('width' in parameters) {
    const params: ICubeParams = parameters;
} else { 
    /* Now what ? Handle unexpected case or ignore it, up to you */ 
}

【讨论】:

  • 不错的一个。在这种情况下,instanceof 可以用作类型保护吗?属性width 可能会随着时间的推移而改变或被删除,如果可以使用instanceof,它会是更好的类型保护选择吗?
  • @MehmetSeckin No. instanceof 可以用作类的类型保护。接口被删除并且在运行时不存在,javascript instanceof 运算符需要一个类才能工作。
猜你喜欢
  • 2021-03-25
  • 2019-02-08
  • 2023-01-18
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
  • 2016-08-26
相关资源
最近更新 更多