我正在測驗各種打字稿型別,直到遇到以下情況。
為什么可以Record<string, any>相等函式?
type C = { [key: string]: any } // Record<string, any>;
const C0: C = undefined // error
const C1: C = null // error
const C2: C = 2 // error
const C3: C = 'hello world' // error
const C4: C = { foo: 'bar' } // ok
const C5: C = () => undefined // ok
還是Records<string, unknown>不行?
type B = { [key: string]: unknown } // Record<string, unknown>;
const B0: B = undefined // error
const B1: B = null // error
const B2: B = 2 // error
const B3: B = 'hello world' // error
const B4: B = { foo: 'bar' } // ok
const B5: B = () => undefined // error
打字稿游樂場
uj5u.com熱心網友回復:
Record<string, any>是可分配性的特殊情況,它基本上意味著任何物件型別。這在這個 GitHub 問題中有解釋
通常,如果目標型別有,則源型別必須具有索引簽名,但是對于 : any 確實沒有任何暗示(根據定義,每個屬性都必須與 any 匹配),因此我們將 [s: string]: any 設為無操作出于可分配性的原因。這啟用了一些以前不起作用的模式:
function doSomething(obj: { [s: string]: any}) {
// ...
}
const obj = { a: 1, b: 2 };
// WAS ERROR: 'obj' lacks index signature
doSomething(obj);
這在某些情況下會產生一些不良的可分配性,因此我們沒有將此規則應用于 : unknown 以便您可以選擇您想要的行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/384524.html
標籤:javascript 打字稿 功能 目的
下一篇:從多個物件中計算相同的屬性值
