理解 Typescript 中的嵌套尖括号

Understanding nested angle brackets in Typescript

我正在阅读一本关于 Typescript 的书,并且我很难确定 operations/castings 是用“<>”制作的。

例如,在下面的代码中,我不确定将什么声明为 WrappedComponent 的类型。

它是否是一个也有 PropsWithChildren 和一个 initialState 的 ComponentType 属性?真不知道怎么读

我应该如何解析它?感谢任何帮助

import React, { PropsWithChildren, ComponentType } from 'react';
import { AppState } from './context/AppStateContext';

export const withData = (
  WrappedComponent: ComponentType<PropsWithChildren<{ initialState: AppState }>>
) => {
  // function code
};

尖括号之间的是类型被传递给通用的东西。

一种思考方式是查看 JavaScript 中的链式函数调用:

foo(bar(123))

上面将 123 传递给 bar,然后将该调用的结果传递给 foo。 TypeScript 中的嵌套尖括号做类似的事情;内部类型首先求值,然后它们被传递给外部泛型供 it 解析。

所以,这个:

export const withData = (
  WrappedComponent: ComponentType<PropsWithChildren<{ initialState: AppState }>>
) => {

就像在做

type PropsWithChildrenIncludingState = PropsWithChildren<{ initialState: AppState }>;
type WrappedComponent = ComponentType<PropsWithChildrenIncludingState>;
export const withData = (
  WrappedComponent: WrappedComponent
) => {

除了更简洁。

PropsWithChildrenComponentType是泛型;他们接受一个类型参数并使用它来评估不同的类型。

如果您还不熟悉它们,请看一个非常简单的泛型示例:

type WrapInObject<T> = { prop: T };
type WrappedString = WrapInObject<string>;

导致 WrappedString 被解释为类型 { prop: string; }