# tc 基礎類型(基礎型別) 、變量聲明(變數宣告) ###### tags: `4/30 開課` > [基礎類型(基礎型別)](https://www.tslang.cn/docs/handbook/basic-types.html) > [變量聲明(變數宣告)](https://www.tslang.cn/docs/handbook/variable-declarations.html) ### 基礎類型(基礎型別) #### boolean ```typescript let isDone: boolean = false; ``` #### number ```typescript let decLiteral: number = 6; ``` #### string ```typescript let name: string = "bob"; ``` #### Tuple ```typescript let x: [string, number]; x = ['hello', 10]; ``` #### enum ```typescript enum Color {Red, Green, Blue} let c: Color = Color.Green; ``` #### any 可以轉換成任何型別,但在前端使用上需注意 - 補充:例如一些已知的型別如event,在使用上仍會被ts檢查 ```typescript // 為保持event的閱讀性,可以適當給予any const submit = (event: any) => { const submitValue = event.target.value } // 否則,需採用以下嚴謹的寫法 // 轉型 const submit = (event: Event) => { const submitValue = (<HTMLInputElement>event.target).value } // as轉型 const submit = (event: Event) => { const submitValue = (event.target as HTMLInputElement).value } ``` #### Void 沒有回傳東西的時候可以使用 #### Null 和 Undefined - 補充: typescript團隊自己的coding guideline選擇`undefined`作使用,Douglas Crockford thinks null is a bad idea and we should all just use undefined.(提供參考:https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#null-and-undefined) `undefined`可以有兩種允許方式 ```typescript type User = { name: string lastName: string|undefined } type User = { name: string lastName?: string } // 兩種都可接受undefined const admin: User = { name: 'John Doe', lastName: undefined } ``` #### Never - 補充: 沒有終點的函數(函式),例如 throw Exception ```typescript function error(message: string): never { throw new Error(message) } ``` Never和Void的差別 ```typescript let something: void = null; let nothing: never = null; // Error: Type 'null' is not assignable to type 'never' ``` #### var / let / const [hoisting](https://developer.mozilla.org/zh-TW/docs/Glossary/Hoisting) --- ###### tags: `下次 5/14 開課` 範圍:[接口(介面) - 函數(函式)](https://www.tslang.cn/docs/handbook/interfaces.html)
×
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