部份值的型別無法透過原生的 Type 進行定義,這時候可以透過使用 Branded Types (opaque types) 進行額外的型別定義,例如正數、消毒過的字串等。

type Positive = number & {__brand: 'positive'}
type SafeString = string & {__sanitized: true}

在使用的時候則透過 Type Guard 或是 Assertion 使用。

const isPositive = (val: number): val is Positive => {
    return val > 0
}
 
const waitForSeconds = (s: Positive) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true)
        }, s * 1_000)
    })
}
 
const a = 3
if (isPositive(a)) {
    waitForSeconds(a)
}

或是直接透過 as 使用。

只透過註記在型別內處理特殊的資料。

Reference