0

I want to create union type from brother of same interface

like below


interface Foo {
  values: string[];
  defaultValue: string;
}

function fooo({values, defaultValue}: Foo) {}

fooo({values: ['a', 'b'], defaultValue: 'a'}); // this is correct example

fooo({values: ['a', 'b'], defaultValue: 'c'}); // I want to prevent this case!
// defaultValue must be 'a' or 'b'
// like tuple type 'a' | 'b'

Can I do this?

1 Answer 1

1

Sure, you can achieve this by adding generic types.

interface Foo<K extends string[]> {
  values: [...K];
  defaultValue: K[number];
}

function fooo<K extends string[]>({values, defaultValue}: Foo<K>) {}

The generic type K will the tuple type of the value array. We then constrain defaultValue to only have the values specified in values with K[number].

Let's see if it works:

fooo({values: ['a', 'b'], defaultValue: 'a'});
fooo({values: ['a', 'b'], defaultValue: 'c'}); // error: Type '"c"' is not assignable to type '"a" | "b"'

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.