Skip to content

Instantly share code, notes, and snippets.

@mostlylikeable
Created November 30, 2022 16:52
Show Gist options
  • Save mostlylikeable/508a90b3a752ac3c25608a12034eb741 to your computer and use it in GitHub Desktop.
Save mostlylikeable/508a90b3a752ac3c25608a12034eb741 to your computer and use it in GitHub Desktop.
Pick / Omit from an array of field names
type Foo = {
bar: string;
baz: string;
qux: string;
};
// needs to be 'const' / immutable, otherwise ts doesn't know set of values
const includeFields = ['bar', 'baz'] as const;
// dynamic type to create a union of array values
// ==> 'bar' | 'baz'
// - index of an array is type 'number', so this creates a type by collecting
// all values from object keys that are numbers, and for arrays, the index
// is the key.
type IncludedField = typeof includeFields[number];
// dynamic type with fields of 'Foo' who's keys are in `IncludedField'
// ==> { bar: string, baz: string }
type FilteredFoo = Pick<Foo, IncludedField>
const typedPartial: FilteredFoo = {
bar: 'bar value',
baz: 'baz value',
// @ts-expect-error
qux: 'qux value',
};
// @ts-expect-error
typedPartial.qux === 'qux value';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment