TypeScript 联合类型

联合类型在一个值可以是多个类型时使用。

比如当一个属性是 stringnumber


Union | (OR)

使用 | 我们说我们的参数是 stringnumber

实例

function printStatusCode(code: string | number) {
  console.log(`My status code is ${code}.`)
}
printStatusCode(404);
printStatusCode('404');
亲自试一试 »

Union Type Errors

注意:在使用联合类型时,您需要知道您的类型是什么,以避免类型错误:

实例

function printStatusCode(code: string | number) {
  console.log(`My status code is ${code.toUpperCase()}.`) // error: Property 'toUpperCase' does not exist ontype 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'
}

在我们的实例中,我们在调用 toUpperCase() 作为它的 string 方法和 number 无权访问它。

亲自试一试 »

TypeScript 练习

学习训练

训练:

指定函数的参数"myVar"可以是字符串或数字:

function myFunc(myVar:   ) {
console.log(myVar)
}

开始训练