The Required
utility type in TypeScript does not allow selection of specific set of properties. Therefore, you can combine it with the Pick
utility type to select some properties from an existing TypeScript type and make them required. It would have the following syntax:
// TypeScript 2.8+ type RequiredPick = Required<Pick<Type, Keys>>;
You would use it, for example, in the following way:
// TypeScript 2.8+ interface Foo { bar?: string; baz?: number; qux?: boolean; } type Example = Required<Pick<Foo, 'bar' | 'qux'>>;
This would select "bar
" and "qux
" from "Foo
", and make them required in the new type.
You can also create a reusable "RequiredPick
" utility type, like so:
// TypeScript 2.8+ type RequiredPick<T, K extends keyof T> = Required<Pick<T, K>>;
You would use it, for example, in the following way:
interface Foo { bar?: string; baz?: number; qux?: boolean; } type Example = RequiredPick<Foo, 'bar' | 'qux'>; const ex: Example = { bar: 'xyz', qux: true };
If any of the required properties are missing, TypeScript would complain:
// Error: Property '...' is missing in type '...' but required in type '...' const ex1: Example = { }; const ex2: Example = { bar: 'xyz' }; const ex3: Example = { qux: true };
Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.