强制Typescript映射键/值为特定类型



我希望创建一个映射,其中键是一个字符串,值是一个对象,其中每个对象都有一组由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>;

最新更新