簡體   English   中英

TypeScript,從 object 推斷密鑰

[英]TypeScript, infer keys from object

我有一個 object,其中包含應該在新 object 中有效的所有鍵,我需要對所述鍵的值進行一些修改。

例子:

// This object contains all the keys i want to use in a different object below -> "one" and "two".
const myObject: { [id: string]: string } = {
    one: 'foo',
    two: 'bar',
};

這就是我嘗試提取密鑰的方式:

type MyType = {
  [T in keyof typeof myObject]: {
    bar: string
  };
}

如果我在 VSCode 中通過MyType hover 我看到這個:

type MyType = {
    [x: string]: {
        bar: string;
    };
}

這顯然是錯誤的,因為它不應該接受任何字符串,而是myObject中定義的鍵集。

這就是我嘗試使用新類型的方式:

const test: MyType = {
  one: {
    bar: 'foo'
  },
  two: {
    bar: 'string'
  },
  shouldNotBeValid: {
    bar: 'foo'
  }
}

不應允許鍵“shouldNotBeValid”,但它仍然通過。 但是,如果我刪除myObject的類型,那么它是這樣的:

const myObject = {
    one: 'foo',
    two: 'bar',
};

然后 hover over MyType我得到這個是正確的:

type MyType = {
    one: {
        bar: string;
    };
    two: {
        bar: string;
    };
}

是否可以表達MyType我想要的方式,並且仍然能夠繼續輸入myObject

您必須使用通用 function 來創建myObject變量。 通用 function 將類型限制為Record<string, string>但也返回 object 的原始類型。

const myObject = createMyObject({
    one: 'foo',
    two: 'bar',
})

function createMyObject<T extends Record<string, string>>(obj: T) {
  return obj
}

type MyType = {
  [T in keyof typeof myObject]: {
    bar: string
  };
}
// type MyType = {
//     one: {
//         bar: string;
//     };
//     two: {
//         bar: string;
//     };
// }

操場

暫無
暫無

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

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