`extends boolean = false` 的泛型类型是什么意思?

What does a generic type that `extends boolean = false` mean?

试图理解 API of React Select by looking at its TypeScript definitions 我遇到了这个粗壮的状态定义:

declare type StateManagedSelect = <
  Option = unknown,
  IsMulti extends boolean = false,
  Group extends GroupBase<Option> = GroupBase<Option>
>(
  props: StateManagerProps<Option, IsMulti, Group> &
    RefAttributes<Select<Option, IsMulti, Group>>
) => ReactElement;

有两件事让我印象深刻:

  1. IsMulti extends boolean = false 被分配了一个实际的 ?!这是什么意思?我认为 TS 类型泛型不允许实际的 values,只有默认的 types
  2. Group extends GroupBase<Option> = GroupBase<Option>。将默认类型分配给 Group 是否与它扩展的东西相同?难道不只是 Group extends GroupBase<Option>,期间?

T extends X = Y,其中 YX 的子类型,只是给出 T 的默认类型。 boolean 等同于 true | false,因此 falseboolean.

的子类型

这是一个简化的例子。不使用默认子类型:

declare function fn<T extends boolean>(arg?: T): T

let x = fn(true) // type of `x` is `true`
let y = fn(false) // type of `y` is `false`
let z = fn() // type of `z` is `boolean`

现在使用默认子类型:

declare function fn<T extends boolean = false>(arg?: T): T

let x = fn(true) // same as before
let y = fn(false) // same as before
let z = fn() // type of `z` is now `false`
  1. IsMulti extends boolean = false is assigned an actual value?! What does this mean? I thought TS type generics did not allow for actual values, only default types

false 是一种类型(true 也是)。它们是 literal types,都是 boolean 的子类型。从 link(你必须向下滚动一点):

There’s one more kind of literal type: boolean literals. There are only two boolean literal types, and as you might guess, they are the types true and false. The type boolean itself is actually just an alias for the union true | false.

所以 IsMulti extends boolean = false 的意思是 IsMulti 类型参数需要一个 boolean 类型参数(truefalse),如果你不要提供它,它默认为 false.

类型
  1. Does assigning a default type to Group that is identical to the thing it extends do anything? Could it not just have been Group extends GroupBase<Option>, period?

是的,它做了一些事情:让它成为可选的。如果它只是 Group extends GroupBase<Option>,则在使用 StateManagedSelect 时必须为其提供类型参数。因为类型参数有默认值,所以你没有。