英文:
How to ensure object values contain their key with TypeScript?
问题
使用TypeScript的文字类型,我能够确保对象值由Color
和字符串-primary
组成。
type Color = "green" | "blue" | "orange" | "red" | "purple" | "pink";
type ColorObject<Key extends string = Color> = Record<Key, `${Key}-primary">;
const COLORS: ColorObject = {
green: "green-primary",
blue: "blue-primary",
orange: "orange-primary",
red: "red-primary",
purple: "purple-primary",
pink: "pink-primary"
};
但我想确保值与键相同,即:
pink: "pink-primary" // 好
pink: "red-primary" // 不好
我进行了相当多的搜索,不确定在我写这个回答的时候是否可能... 有什么想法吗?
英文:
Using TypeScript literal type, I'm able to ensure that the object values are made of a Color
and the string -primary
.
type Color = "green" | "blue" | "orange" | "red" | "purple" | "pink";
type ColorObject<Key extends string = Color> = Record<Key, `${Key}-primary`>;
const COLORS: ColorObject = {
green: "green-primary",
blue: "blue-primary",
orange: "orange-primary",
red: "red-primary",
purple: "purple-primary",
pink: "pink-primary"
};
But I would like to ensure that the value is the same as the key, i.e:
pink: "pink-primary" // good
pink: "red-primary" // bad
I searched quite a lot, not sure it's possible as the time I write this... Any ideas?
答案1
得分: 3
你应该使用mapped types来实现这个目标。在你当前的实现中,你的类型允许任何字符串颜色具有值中的任何颜色。相反,通过使用映射类型,我们将分别映射颜色并为它们分配相应的值:
type Color = 'green' | 'blue' | 'orange' | 'red' | 'purple' | 'pink';
type ColorObject<Key extends string = Color> = {
[K in Key]: `${K}-primary`;
};
const COLORS: ColorObject = {
green: 'green-primary',
blue: 'orange-primary', // 预期错误
orange: 'orange-primary',
red: 'red-primary',
purple: 'purple-primary',
pink: 'pink-primary',
};
<details>
<summary>英文:</summary>
You should use [mapped types](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html) to achieve it. In your current implementation, your type allows any string color to have any of the colors in the value. Instead by using mapped typed we will map through the colors separately and assign the corresponding value to them:
type Color = 'green' | 'blue' | 'orange' | 'red' | 'purple' | 'pink';
type ColorObject<Key extends string = Color> = {
[K in Key]: ${K}-primary
;
};
const COLORS: ColorObject = {
green: 'green-primary',
blue: 'orange-primary', // expected error
orange: 'orange-primary',
red: 'red-primary',
purple: 'purple-primary',
pink: 'pink-primary',
};
[playground](https://www.typescriptlang.org/play?ts=5.0.4#code/C4TwDgpgBAwg9gGzgJygXigcgObIhAO0ygB8sAjBAVwmLMxQEMDtbSs8ATOrMK5MAjb0wASwIBrTAG4AUKEixEKAPLkAVhADGwADwBpCCCgQAHsEKcAzlCvBk47OiVJkAPmcBvWVCgBtfShxKEMQAF0ALigAAwAST30AXwBaMAcAW0ZkEGi5RLlZLTgCO1gVABkVACUAZSj4VzVNHS8fKFx8AiicPEJUjKyQTAAaNsoabqYWCH7RTOyRqAB6JZNTSB0IThNkZBQ2qdZJ5GZWWfmh0d8ubq5zwZG2vgEhbufBGbS5h6uoMUk3uIJPcFqN8rIgA)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论