简体   繁体   中英

How to define mapped type in flow as defined in typescript

Mapped types

https://www.typescriptlang.org/docs/handbook/advanced-types.html

A common task is to take an existing type and make each of its properties optional:

interface PersonPartial {
    name?: string;
    age?: number;
}

Or we might want a readonly version:

interface PersonReadonly {
    readonly name: string;
    readonly age: number;
}

This happens often enough in Javascript that TypeScript provides a way to create new types based on old types — mapped types. In a mapped type, the new type transforms each property in the old type in the same way. For example, you can make all properties of a type readonly or optional. Here are a couple of examples:

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
}

type Partial<T> = {
    [P in keyof T]?: T[P];
}

And to use it:

type PersonPartial = Partial<Person>;
type ReadonlyPerson = Readonly<Person>;

How to define such type in flow ?

For readonly, there is the $ReadOnly utility type . It's worth noting that this does not work recursively for nested objects. It also does not change the face that each of those is optional, which makes sense since you're setting it once and saying you can't change it.

interface PersonPartial {
  name?: string;
  age?: number;
}

type ReadOnly = $ReadOnly<PersonPartial>

For making things optional and not readonly, you can just spread the readonly into a new type:

interface PersonReadOnly {
  +name: string,
  +age: number
}

type PartialPerson = { ...PersonReadOnly }

Here's the try flow that has all of this.

You could always make you're own types that implement these as well. So if you wanted a Partial type, you could just:

type Partial<O: {}> = { ...O }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM