[英]Force Typescript Map key/value to be of a certain type
我希望創建一個映射,其中鍵是字符串,值是對象,其中每個對象都有一組由 mapValue 描述的值。
type mapValue
{
first: string;
second: boolean;
}
這可能嗎?
有幾種方法可以做到這一點,聽起來您需要閱讀一些 TypeScript 文檔才能更好地了解您在做什么。 如果你來自 JavaScript,我建議你閱讀這篇簡短的文章(然后閱讀網站的其余部分......🤓)。
在另一種類型中使用您的類型很容易:
type MapValue = {
first: string;
second: boolean;
};
// when you know the expected properties
type AnotherThing = {
id: string;
content: string;
thing: MapValue;
};
// when you want a flexible object type indexed by strings, with a fixed value
type AnotherThing = {
[key: string]: MapValue;
};
// bonus points - use a typescript utility for a shorthand version of the above
type AnotherThing = Record<string, MapValue>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.