简体   繁体   中英

TypeScript - enforce types of specific keys in object

I am using typescript and right now defining an interface that looks like that:

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

T can be object with any form, but it has to contain label and key of strings, so I would like to enforce T[labelKey] and T[valueKey] to be strings. How can I do that?

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

I would say the simplest way to do this is to define a base interface and then do the following:

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

interface SelectProps<T extends BaseSelectProps> {
    options: T[];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM