TypeScript 联合类型
当一个值可以是多个类型时,使用 联合类型(Union Type)。
例如,当属性是字符串或数字时。
Union | (OR)
使用 | ,当参数是字符串或数字时:
实例
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 on type 'string | number'. Property 'toUpperCase' does not exist on type 'number'}
在我们的实例中,调用 toUpperCase() 作为 string 方法时遇到了出现错误,因为 number 会失败。