我想為具有string鍵和任意值的物件創建型別。因此,我想要的型別(我們稱之為Obj)應該會導致以下obj物件的型別錯誤,因為它的鍵是型別number:
const obj: Obj = {
1: "foo" // I'd expect a TS error here because the key 1 is of type `number` and not `string`
};
但是,我所有的嘗試都不會導致任何 TS 錯誤!這是我的三個嘗試:
- 內置
Record型別(隱式使用in運算子):
type Obj = Record<'1', any>;
const obj: Obj = {
1: "foo" // TS error expected! ?
};
- 映射型別(重新創建
Record型別):
type Obj = { [key: string]: any };
const obj: Obj = {
1: "foo" // TS error expected! ?
};
- 通過以下方式
Record進行鍵重映射的as自定義型別:
type MyRecord<K extends string, T> = {
[P in K as string]: T;
};
type Obj = MyRecord<string, any>;
const obj: Obj = {
1: "foo" // TS error expected! ?
};
- 即使使用文字型別
'1'也不會強制將鍵設為'1',但允許使用數字1:
type Obj = Record<'1', any>;
const obj: Obj = {
1: "foo" // TS error expected! ?
};
這通常是可能的,還是由于 JavaScript 物件的某些屬性而無法實作?
我的代碼的 TS Playground。
uj5u.com熱心網友回復:
通過TypeScript 檔案的keyof頁面
JavaScript 物件鍵總是被強制轉換為字串,因此 obj[0] 始終與 obj["0"] 相同
所以實際上{1: "foo"}是一樣的{"1": "foo"}。
uj5u.com熱心網友回復:
定義物件字面量時,1被強制轉換為string( "1")。您不能使用number鍵定義物件:
const obj = {
prop: 'value',
1: 'another value',
};
for (const key in obj) {
console.log(key, typeof key);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404540.html
標籤:
