Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapped typed to make all properties required

Tags:

typescript

A TypeScript class can have optional properties and required properties.

class SomeClass {
  foo?: string;
  bar?: string;
  baz: string = '';
  qux: string = '';
}

The Partial<T> mapped type can make all the properties optional.

type SomeClassPartial = Partial<SomeClass>;

The question is, can we go the opposite way and make all the properties required?

type SomeClassComplete = Complete<SomeClass>;

The Partial mapped type adds a ? to all the properties, thereby making them all optional. What I am looking for is a way to remove the ? from all the properties, thereby making them all required.

We tried using the ! operator but it is doesn't have that semantic.

type Complete<T> = {
  [P in keyof T]: T[P];
};
like image 408
Shaun Luttin Avatar asked Oct 18 '18 22:10

Shaun Luttin


People also ask

How do you construct a type or interface with all its properties optional in TypeScript?

Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!

What is the difference between interface and type in TypeScript?

The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object.

How do I create a map in TypeScript?

Creating a MapUse Map type and new keyword to create a map in TypeScript. let myMap = new Map<string, number>(); To create a Map with initial key-value pairs, pass the key-value pairs as an array to the Map constructor.


1 Answers

Found it. The Required<T> partial does this.

The definition is inside TypeScript/lib.es5.d.ts here.

/**
 * Make all properties in T required
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};
like image 157
Shaun Luttin Avatar answered Sep 23 '22 11:09

Shaun Luttin