Typescript提供“ string”类型而不是“ string | null”-vscode

时间:2019-02-27 06:12:19

标签: typescript visual-studio-code

Typescript推断错误的类型

我希望“某物”的类型为"string |null",但是vscode给出的是"string"

我正在使用打字稿3.3

interface S {
 // wrong expectation : "something" has type of string
 something : string | null
}

screenshot vscode

2 个答案:

答案 0 :(得分:0)

因为它是定义。

  

默认情况下,null和undefined是所有其他类型的子类型。这意味着您可以将null和undefined分配给数字。

https://www.typescriptlang.org/docs/handbook/basic-types.html

答案 1 :(得分:0)

感谢@Nail Achmedzhanov在原始问题下的评论。

这是因为“空严格检查”设置为false。

设置为true应该可以解决我的问题。 (覆盖反应本机打字稿设置的查找方法)

{
  "compilerOptions": { 
    "strictNullChecks": true,              /* Enable strict null checks. */
}