具有相等运算符的打字稿泛型类型是什么意思? [英] typescript generic type with equal operator means?

查看:36
本文介绍了具有相等运算符的打字稿泛型类型是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习打字稿泛型,并遇到以下泛型类型与扩展类型的相等运算符

I am learning typescript generic, and come across the following generic type with the equal operator for extends type

export interface DataType {
  [key: string]: FieldValue;
}

export interface FormProps<Data extends DataType = DataType> { }

DataType = DataType 在这里是什么意思?

推荐答案

如果您不提供类型 Data(必须 扩展 DataType),默认为DataType.

If you don't provide a type Data (which must extend DataType), it will default to DataType.

来自之前的发行说明

考虑一个创建新 HTMLElement 的函数,不带参数调用它会生成一个 Div;您也可以选择传递子项列表.以前,您必须将其定义为:

Consider a function that creates a new HTMLElement, calling it with no arguments generates a Div; you can optionally pass a list of children as well. Previously you would have to define it as:

declare function create(): Container<HTMLDivElement, HTMLDivElement[]>;
declare function create<T extends HTMLElement>(element: T): Container<T, T[]>;
declare function create<T extends HTMLElement, U extends HTMLElement>(element: T, children: U[]): Container<T, U[]>;

使用通用参数默认值,我们可以将其简化为:

With generic parameter defaults we can reduce it to:

declare function create<T extends HTMLElement = HTMLDivElement, U = T[]>(element?: T, children?: U): Container<T, U>;

通用参数默认遵循以下规则:

A generic parameter default follows the following rules:

  • 如果类型参数具有默认值,则该类型参数被视为可选.
  • 必需的类型参数不能跟在可选的类型参数后面.
  • 类型参数的默认类型必须满足类型参数的约束(如果存在).
  • 指定类型参数时,您只需为所需的类型参数指定类型参数.未指定的类型参数将解析为其默认类型.
  • 如果指定了默认类型并且推理无法选择候选者,则推理默认类型.
  • 与现有类或接口声明合并的类或接口声明可能会为现有类型参数引入默认值.
  • 与现有类或接口声明合并的类或接口声明可以引入新的类型参数,只要它指定默认值即可.

这篇关于具有相等运算符的打字稿泛型类型是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆