TypeScript-强制对象中特定键的类型

我使用的是打字稿,现在定义的接口看起来像这样:

interface SelectProps<T> {
    options: T[];
    labelKey: keyof T;
    valueKey: keyof T;
}

T可以是任何形式的对象,但它必须包含字符串的标签和键,因此我想将T[labelKey]T[valueKey]强制为字符串。我该怎么办?

liaozhongfa 回答:TypeScript-强制对象中特定键的类型

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'
}

,

我想说的最简单的方法是定义一个基本接口,然后执行以下操作:

interface BaseSelectProps {
    valueKey: string;
    labelKey: string;
}

interface SelectProps<T extends BaseSelectProps> {
    options: T[];
}
本文链接:https://www.f2er.com/3167621.html

大家都在问