如何按照打字稿中的定义在流中定义映射类型

罗希特·班萨尔(Rohit Bansal)

映射类型

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

一个常见的任务是采用一个现有的类型并将其每个属性设为可选:

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

或者我们可能想要一个只读版本:

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

这种情况在Javascript中经常发生,TypeScript提供了一种基于旧类型(映射类型)创建新类型的方法。在映射类型中,新类型以相同的方式转换旧类型中的每个属性。例如,您可以将类型的所有属性设置为只读或可选。以下是几个示例:

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

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

并使用它:

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

如何在流中定义这种类型?

卡利

对于只读,有$ReadOnly实用程序类型值得注意的是,这不适用于嵌套对象。它还不会改变每个选项都是可选的外观,这很有意义,因为您只设置了一次就说不能更改。

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

type ReadOnly = $ReadOnly<PersonPartial>

为了使事情成为可选的而不是只读的,您可以将只读扩展为新的类型:

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

type PartialPerson = { ...PersonReadOnly }

是具有所有这些功能的尝试流程

您总是可以使自己成为实现这些类型的自己的类型。因此,如果您想要一种Partial类型,则可以:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章