(1) TypeScript: Create Optional Types From Old Types?

Taric Ov
1 min readJan 20, 2024

--

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: "sad"}
// 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:

--

--

Taric Ov
Taric Ov

Written by Taric Ov

software eng. 🎧 i build something new every week 🥷 samurai 😀 radio-ist @thesamuraination.com 🎙️ ai hassler 🤖

No responses yet