我正在使用 typescript ,现在正在定义一个看起来像这样的界面:
interface SelectProps<T> {
options: T[];
labelKey: keyof T;
valueKey: keyof T;
}
T 可以是任何形式的对象,但它必须包含字符串的标签和键,所以我想强制执行 T[labelKey]
和 T[valueKey]
成为字符串。我该怎么做?
最佳答案
type Option<LabelKey extends string, ValueKey extends string> =
Record<string, any> & Record<LabelKey | ValueKey, string>
interface SelectProps<LabelKey extends string, ValueKey extends string> {
options: Option<LabelKey, ValueKey>[];
labelKey: LabelKey;
valueKey: ValueKey;
}
const props: SelectProps<'foo', 'bar'> = {
options: [{ foo: '', bar: '', extra: 3 }],
labelKey: 'foo',
valueKey: 'bar'
}
关于javascript - TypeScript - 强制执行对象中特定键的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58691242/