To make all properties of an existing TypeScript type required, starting with TypeScript 2.8, you can simply use the Required
utility type, which has the following syntax:
// TypeScript 2.8+ Required<Type>
This would strip the ?
modifiers from all properties of a type, making them all required.
For example, you can use the Required
utility type in the following way:
// TypeScript 2.8+ interface Foo { bar?: string; baz?: number; qux?: boolean; } type RequiredFoo = Required<Foo>;
You could use this type in the following way:
const foo: RequiredFoo = { bar: 'abc', baz: 123, qux: false };
If any of the required types are missing, it will throw an error, like in the following case:
// TypeScript 2.8+
// Error: Property 'qux' is missing in type '{ bar: string; baz: number; }' but required in type 'Required<Foo>'.
const foo: RequiredFoo = { bar: 'abc', baz: 123 };
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.