簡體   English   中英

是否可以推斷預定義的 object 的鍵?

[英]Is it possible to infer the keys of an object that is predefined?

我有一個 object:

const obj = {
    a: {...},
    b: {...},
    ...
}

在 ts 中,如果我要創建一個類型:

type oT = keyof typeof obj;

我會得到鑰匙的聯合..

我想將'obj'定義為記錄類型,例如

type myType = Record<string, IMyInterface>;
const obj: myType ={...}

但仍然推斷出 ot 類型的密鑰,我該怎么做?

你可以試試

const _obj = {
    a: { name: 'alex' },
    b: { age: 1 },
    c: 'hello',
}
type oT = keyof typeof _obj;
const obj = _obj as Record<oT, any>; // use obj going forward

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM