Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active October 3, 2023 15:27
Show Gist options
  • Save tlux/96e128a60397cd84b6784d13edba422a to your computer and use it in GitHub Desktop.
Save tlux/96e128a60397cd84b6784d13edba422a to your computer and use it in GitHub Desktop.
Extract fields of a specific type from a Record in TypeScript
type AllowedFieldsWithType<TObj, TKey> = {
[K in keyof TObj]: TObj[K] extends TKey ? K : never;
};
export type FieldsOfType<T, K> = AllowedFieldsWithType<T, K>[keyof T];
// Usage Example:
//
// const obj = {
// foo: 'bar',
// bar: 123,
// baz: 'hello!',
// boom: false,
// }
//
// type MyRecord = typeof obj;
// type StringFields = FieldsOfType<MyRecord, string>; # => "foo" | "baz"
// type OtherFields = FieldsOfType<MyRecord, number | boolean>; # => "bar" | "boom"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment