字典键作为可接受的属性值



我已经创建了这样一个字典:

const iconTypesDictionary: { [key: string]: IconPrefix } = {
solid: 'fas',
regular: 'far',
light: 'fal',
}

我想使用这个字典的键作为属性的可能值。在这个例子中,要替换重复的键:

export interface IconProps {
type?: 'solid' | 'regular' | 'light';
}

有解决方案吗?

直到我们在TS中获得satisfies(参见ms/TS#47920和ms/TS#46827等)之前,您可以使用受约束的恒等函数来确保您定义的字典符合您期望的类型,同时还保留其类型信息。在创建对象值之后,您只需要使用keyof typeof value来获得表示其键的类型:

TS操场

// You didn't share this type so I am using this as an example:
type IconPrefix = 'fal' | 'far' | 'fas';
// Using this function allows you to constrain an argument value's type,
// while also preserving its actual type information:
function createConstrainedIdFn <T>(): <Value extends T>(value: Value) => Value {
return value => value;
}
// Use it like this:
// (note the double invocation and that the value argument goes in the second parentheses)
const iconTypesDictionary = createConstrainedIdFn<Record<string, IconPrefix>>()({
solid: 'fas',
regular: 'far',
light: 'fal',
}); /* type is:
{
solid: "fas";
regular: "far";
light: "fal";
}
*/
type IconTypesDictKey = keyof typeof iconTypesDictionary; // "solid" | "regular" | "light"
type IconProps = {
type?: IconTypesDictKey;
};

最新更新