0

I am attempting to constrain an array's values to particular keys of an interface:

interface Foo {
  bar: string;
  baz: number;
  foo: string;
}

type ExtractArrayOfKeys<T, K extends keyof T> = Pick<T, K>[];

const keyArray: ExtractArrayOfKeys<Foo, "bar" | "baz"> = ["bar", "baz"]; // Error: Type 'string' is not assignable to type 'Pick<Foo, "bar" | "baz">'
4
  • Array<keyof Foo> Commented Nov 26, 2020 at 14:41
  • @bugs I wish to pick particular keys... So in the above, how could I type the array to allow bar and baz as valid entries, but disallow foo? Commented Nov 26, 2020 at 14:44
  • Sorry, I misread the question... Commented Nov 26, 2020 at 14:47
  • No worries, all good :) Commented Nov 26, 2020 at 14:48

1 Answer 1

1

This can be done relatively easily with the Extract utility type, something like

type AllFoo = keyof Foo
type BarBaz = Extract<keyof Foo, 'bar' | 'baz'>

const allFooOK: AllFoo[] = ['bar', 'baz', 'foo']
const allFooNotOK: AllFoo[] = ['bar', 'kek'] // Type '"kek"' is not assignable to type '"bar" | "baz" | "foo"'

const barBazOK: BarBaz[] = ['bar', 'baz']
const barBazNotOK: BarBaz[] = ['bar', 'foo'] // Type '"foo"' is not assignable to type '"bar" | "baz"'.

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.