MST

星途 面试题库

面试题:TypeScript宽进严出策略之类型推断

在TypeScript中,以下代码在执行`func`函数时会发生什么?请解释原因。 ```typescript function func(a: number | string) { let result = a.length; return result; } func(10); ```
37.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 代码执行结果
    • 这段代码在执行func(10)时会报错。
  2. 原因解释
    • 在TypeScript中,func函数的参数a的类型被定义为number | string,这是一个联合类型,表示a可以是number类型或者string类型。
    • 然而,number类型并没有length属性,只有string类型有length属性。当调用func(10)时,传入的是number类型的值10,而代码中试图访问a.length,对于number类型来说这是不存在的属性,所以会导致运行时错误。在严格的TypeScript类型检查环境下,代码在编译阶段就会报错,提示Property 'length' does not exist on type 'number | string'. Property 'length' does not exist on type 'number'.