# 【Typescript】聯合型別 (Union Type) ```ts= let myFavoriteNumber: string | number; myFavoriteNumber = 'seven'; myFavoriteNumber = 7; ``` * myFavoriteNumber 可以是 string 或是 number 聯合型別會用 `|` 來分隔每個型別 ## 存取聯合型別的屬性或方法 * length 是 string 的屬性,卻不是 number 的屬性,所以不能直接用 ```ts= function getLength(something: string | number): number { return something.length; } // index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'. // Property 'length' does not exist on type 'number'. ``` * `.toString()` string 和 number 都能使用,所以沒有報錯 ```ts= function getString(something: string | number): string { return something.toString(); } ``` * 聯合型別的變數在被賦值的時候,會根據型別推論的規則推斷出一個型別: ```ts= let myFavoriteNumber: string | number; myFavoriteNumber = 'seven'; console.log(myFavoriteNumber.length); // 5 myFavoriteNumber = 7; console.log(myFavoriteNumber.length); // 編譯時報錯 // index.ts(5,30): error TS2339: Property 'length' does not exist on type 'number'. ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up