Here's a quick tip on how to use already-existing types to create a new type with optional properties without changing the original type:
type ToptionalProps<T> = { [K in keyof T]?: T[K] }; // Example Interface: interface Tuser { id: number; name: string; email: string; } type ToptionalUser = ToptionalProps<Tuser>; // Equivalent to: type ToptionalUser = { id?: number; name?: string; email?: string }; // ==== And you can play around and Pick and Omit like so: ===== type TnameAndIdUser = Omit<Tuser, "email"> type TomittedOptionalProps<T> = { [K in keyof T]?: T[K] }; type ToptionalUser2 = TomittedOptionalProps<TnameAndIdUser>; const newUser: ToptionalUser2 = {email: "newuser@gmail.com"} // Error 'email' does not exist in type 'TpickedOptionalProps<x>';
With this trick, you can now easily create a type where all properties of the original type become optional.
Ts Playground:
Top comments (0)