【问题标题】:Type 'undefined' is not assignable to type 'number' .ts(2322)类型“未定义”不可分配给类型“数字”.ts(2322)
【发布时间】:2020-10-28 04:55:24
【问题描述】:

我一直在学习 Typescript 语言,需要一些解释。问题是名为this.value 的变量永远不会分配为未定义,因为isValid 函数检查它。如何让 typescript 看懂?

export const isValid = (n: any) => n && n > 0 && n < 10;

class Test {
    value: number;
    constructor(value?: number) {
        /*
        Type 'number | undefined' is not assignable to type 'number'.
        Type 'undefined' is not assignable to type 'number'.ts(2322)
        */
        this.value = isValid(value) ? value : -1;
    }
}

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    由于构造函数中的value 是可选的。它的类型是number | undefined,你需要在分配它时将它转换为数字:

     this.value = isValid(value) ? value as number : -1 ;
    

    【讨论】:

    • 可以,但看起来不安全。以后改了IsValid函数表达式忘记去掉as numbercast..还有别的办法解决吗?
    • as number 用于value 而不是isValid(value)。这样做的方法是删除 value 作为可选。
    【解决方案2】:

    默认情况下,类型检查器不查看被调用函数的实现,只查看它们的签名。因此,构造函数的类型检查器不知道 isValid 只有在 n 是数字时才会返回 true。

    您可以将isValid 的代码内联到构造函数中:

    constructor(value) {
      this.value = value && value > 0 && value < 10 ? value : -1;
    }
    

    或者用user defined type guard扩展isValid的函数签名:

    export function isValid(n: any): n is number {
      return n && n > 0 && n < 10;
    }
    

    【讨论】:

    • 这就是我要找的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2021-01-12
    • 2021-12-05
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多