深入對(duì)象
索引簽名(Index Signature)
我們已經(jīng)很熟悉了
type Hash = {
[key: stirng]: unknown;
length: number;
}
type List {
[key: number]: unknown;
length: number;
}
映射類(lèi)型(Mapped Type)
多用于泛型
type List {
[key in string]: unknown;
}
type List {
[key in number]: unknown;
}
可選類(lèi)型
對(duì)象的某個(gè)屬性可用可不用
interface Person {
name: string;
age: number;
onChange?: () => void;
}
const p: Person = {
name: 'hi',
age: 18
}
只讀類(lèi)型
表示只讀蟋滴,不能寫(xiě)
interface Person {
name: string;
age: number;
readonly id: number;
}
const p: Person = {
name: 'hi',
age: 18,
id: 1,
}
p.name = 'new name'
p.id = 2 // TODO: 報(bào)錯(cuò)底燎,Cannot assign to 'id' because it is a read-only property.ts
深入函數(shù)
對(duì)象的語(yǔ)法全都適用于函數(shù)辉哥,函數(shù)也可以用對(duì)象來(lái)聲明
type F = {
(a: number, b: number) => void;
count: number;
}
// 普通聲明
type F1 = (a: number, b: number) => void
聲明方式
JS 函數(shù)的三種聲明方式
function f1(a) {
/* ... */
}
const f2 = function(a) {
/* ... */
}
const f3 = () => {
/* ... */
}
那么相對(duì)應(yīng) TS 的
function f1(a: number): number {
/* ... */
}
const f2 = function (a: number): number {
/* ... */
}
const f3 = (a: number): number => {
/* ... */
}
// 也可以把類(lèi)型提取出來(lái)系羞,寫(xiě)在等號(hào)左邊,比較推薦
type F2 = (a: number) => number
const f2: F2 = function (a) {
/* ... */
}
可選參數(shù)
function addEventListener(eventType: string, fn: unknown, useCapture?: boolean) { // TODO: 加上問(wèn)號(hào)就好了
/* ... */
}
addEventListener('click', () => 1)
參數(shù)默認(rèn)值
實(shí)際情況我們會(huì)更傾向于使用默認(rèn)值
// 和上面的代碼等價(jià)
function addEventListener(eventType: string, fn: unknown, useCapture=false) {
/* ... */
}
addEventListener('click', () => 1)
返回值也是函數(shù)
type Add = (x: number) => (y: number) => number
const add: Add = a => b => a + b