TypeScript 新語法 — satisfies

janlin002
4 min readDec 11, 2023
Photo by Timothy Cuenat on Unsplash

其實說新語法也有點牽強,畢竟在去年 11 月份 也就是 typeScript 的 4.9 版就已經發布了,只是最近才關注到這個語法,並且解決了我很多開發時的不方便,所以就把它記錄下來

開始前,先給大家一個簡單的情境

type Type = {
amount: number | string
}

const record: Type = {
amount: 123.11,
}

console.log(Math.floor(record.amount))

這樣的寫法,邏輯感覺是行得通的,但是 TypeScript 卻會報錯

Argument of type 'string | number' is not assignable to parameter of type 'number'.
Type 'string' is not assignable to type 'number'.

原因是因為 TypeScript 認為 amount 有可能為 string 但是你對他做一個 number 才有的操作(Math.floor()),所以就報錯了

那怎麼解決?

很簡單,就用 as !!!

如果把上面的程式碼改成用 as ,就不會報錯了

type Type = {
amount: number | string
}

const record: Type = {
amount: 123.11,
}

console.log(Math.floor(record.amount as number))

但使用 as 也有很大的缺點,除了很不直觀以外,他也讓你的 code 脫離了 TypeScript 的驗證,所以只有在你對自己所做事情非常有把握的情況下,才會使用到 as ,以我個人的開發經驗來說,當使用到 as 時,通常是開發者個人問題

satisfies

現在要來介紹 satisfies ,一個可以取代 as 的新語法

先說一下結論: satisfies 這個語法,可以讓 TypeScript 去自適應型別

一樣拿上面的例子來說

type Type = {
amount: number | string
}

const record= {
amount: 123.11,
} satisfies Type

console.log(Math.floor(record.amount))

如果改成上面這個寫法的話,就不會在報錯,並且把滑鼠滑到 record.amount 時,會發現它自動認定我們的 amountnumber !!

那現在嘗試改成 string 的寫法,看會不會一樣認定為正確的型別

type Type = {
amount: number | string
}

const record= {
amount: 'Apple, Banana, Kiwi',
} satisfies Type

console.log(record.amount.slice(7))

一樣把滑鼠滑到 record.amount 確認一下型別,這時候 TypeScript 會認定為 string !!!

結論

satisfies 是一個非常好的新語法,解決了過去可能會一直使用 as 的情況,或許下次開發到需要使用 as 前,可以先考慮是否能夠替換成 satisfies

這邊附上程式碼,有興趣的話可以去玩玩看,TypeScript playground

--

--