Naor
Naor

Reputation: 24053

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?

Upvotes: 1

Views: 517

Answers (2)

Nour
Nour

Reputation: 5889

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[];
}

Upvotes: 0

Emil Laine
Emil Laine

Reputation: 42828

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

Upvotes: 2

Related Questions