個人的理解是typescript就是es+類型檢查,首先我們看一個最簡單的例子
interface InnerErrorProps {
code: number
}
const InnerError = (props: InnerErrorProps) => <h1>i am {props.code}</h1>
export const Errors = () => <InnerError code={405} />
- 在這里我們定義了兩個組件撕贞,一個是InnerError堤框, 一個是Errors。Errors是InnerError的父組件昆汹,并且傳入一個code作為子組件的props。
- 子組件接收一個參數(shù)婴栽,參數(shù)是key满粗,value格式,key表示傳入的參數(shù)值愚争,value則表示值的類型映皆。
- InnerErrorProps即參數(shù)所定義的類型挤聘。
元組:定義一個已知元素數(shù)量和元素類型的數(shù)組
let x: [string, number, any]
枚舉:
- 枚舉類似于對象,會默認(rèn)給每一項增加一個元素編號捅彻,枚舉的第一項為0组去,依次遞增
enum Color = { blue, red, green }
- 當(dāng)然也可以給枚舉指定元素編號, 其中red的元素編號是3
enum Color = { blue = 2, red, green=5 }
- 根據(jù)枚舉項獲取元素編號
let x: Color = Color.red
console.log(x) // 3
- 根據(jù)元素編號獲取枚舉項
let x: string = Color[3]
console.log(x) // 'red'
類型斷言
以下是兩種類型斷言的方式
let numValue: any = 'i am mana'
// 第一種
let valueLength = (<string>numValue).length
// 第二種, jsx只能用第二種
let valueLength = (numValue as string).length
- 關(guān)于類型斷言,官網(wǎng)沒有解釋太多步淹,我個人的理解是从隆,在執(zhí)行某一行代碼時,能夠讓編譯器和讀者更精確的知道代碼如何執(zhí)行缭裆。