Indexed Type Extraction
Source code
type SetStateInternal<T> = {
_(
partial: T | Partial<T> | { _(state: T): T | Partial<T> }['_'],
replace?: false,
): void
_(state: T | { _(state: T): T }['_'], replace: true): void
}['_']這個小技巧是用 ['_'] 來提取了 object 裡面的 type
type Test ={ _(a:number, b:number):number
_(a:string, b:string):void
}['_']
const A:Test = (a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a + b
}
if (typeof a === 'string' && typeof b === 'string') {
console.log(a, b)
}
throw new Error('Invalid arguments')
}

-
避免多餘的物件包裝
直接取得函數型別,不需要再包一層物件。 -
支援多重簽名(Overload)
這種寫法可以讓你定義多個函數簽名(像 TypeScript 的 overload),然後直接取得這個「多重簽名」的型別。 -
型別推斷更精確
這樣寫可以讓 TypeScript 準確推斷出你要的函數型別,避免型別不一致或推斷錯誤。 -
型別複用與擴展性高
你可以很容易地複用這個技巧來定義其他 API 的型別,維護起來更方便。