【问题标题】:In TypeScript, when invoking a function, why can I hint that a null argument has some other type?在 TypeScript 中,调用函数时,为什么我可以提示 null 参数具有其他类型?
【发布时间】:2020-08-19 06:51:46
【问题描述】:

我试图了解 TypeScript 行 A 是如何编译而 B 行不编译的。

function someFunction<T>(arg: T): void {
  console.log(arg)
}

someFunction<string>('some string') // obviously, it works
someFunction<string>(null)          // [A] compiles
someFunction<string>(2)             // [B] doesn't compile

A 行中,我暗示编译器该参数是string 类型,而显然不是。然而,TypeScript 将编译该行而不会发出任何错误。

这不会发生在 B 行。我传递了一个 number 并暗示它是一个 string

A 行怎么没有编译失败? null 类型有特殊情况吗?

尽管进行了谷歌搜索,但我找不到令人满意的解释。非常欢迎提供资源链接来解释我的代码中发生了什么。

【问题讨论】:

  • 它在操场上失败,错误:Argument of type 'null' is not assignable to parameter of type 'string'.(2345)。你能发布你的tsconfig.json吗? typescriptlang.org/play?#code/…

标签: typescript


【解决方案1】:

除非启用strictNull 签入tsconfig.json,否则所有类型都隐含undefinednull 类型。所以当你输入string时,基本上就是string | undefined | null。我绝对建议启用该选项,因为它会捕获很多不需要的错误。

您可以在此处阅读更多信息:https://basarat.gitbook.io/typescript/intro/strictnullchecks

【讨论】:

  • 感谢您的回答。我的tsconfig.json 中有strict: true,这意味着strictNullChecks: true。另外,我认为根据您的假设,B 行也会编译,不是吗?
  • 行 B 不会编译,因为 2 是数字,而不是字符串(TypeScript 不会尝试将 2 转换为字符串)。您的解决方案中可能有多个 tsconfig.json 吗?类型检查是否可能在您的编译器中设置为警告?我已经尝试了您的示例,它按预期工作:typescriptlang.org/play?#code/…
  • 您可以检查它是否与泛型无关,只需尝试这样做: const test:string = null; (如果启用了严格,它应该会失败)
  • 其实你是对的,我没有使用strict。感谢您的帮助。
猜你喜欢
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
  • 2021-12-25
  • 2013-05-20
  • 2020-06-12
  • 2023-01-12
相关资源
最近更新 更多