gpt4 book ai didi

具有相等运算符的 typescript 泛型类型意味着什么?

转载 作者:搜寻专家 更新时间:2023-10-30 21:17:01 24 4
gpt4 key购买 nike

我正在学习 typescript 泛型,并遇到了以下泛型类型和扩展类型的相等运算符

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

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

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

最佳答案

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

来自以前的发行说明

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:

  • A type parameter is deemed optional if it has a default.
  • Required type parameters must not follow optional type parameters.
  • Default types for a type parameter must satisfy the constraint for the type parameter, if it exists.
  • When specifying type arguments, you are only required to specify type arguments for the required type parameters. Unspecified type parameters will resolve to their default types.
  • If a default type is specified and inference cannot chose a candidate, the default type is inferred.
  • A class or interface declaration that merges with an existing class or interface declaration may introduce a default for an existing type parameter.
  • A class or interface declaration that merges with an existing class or interface declaration may introduce a new type parameter as long as it specifies a default.

关于具有相等运算符的 typescript 泛型类型意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56843790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com