简体   繁体   English

如何在typescript中定义的流中定义映射类型

[英]How to define mapped type in flow as defined in typescript

Mapped types 映射类型

https://www.typescriptlang.org/docs/handbook/advanced-types.html 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. 这在Javascript中经常发生,TypeScript提供了一种基于旧类型创建新类型的方法 - 映射类型。 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 . 对于readonly,有$ReadOnly实用程序类型 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: 为了使事物可选而不是只读,你可以将readonly传播到一个新类型:

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: 因此,如果您想要一个Partial类型,您可以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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