繁体   English   中英

TypeScript generics,ZA8CFDE6331BD4B62AC96F8911中的function参数的约束

[英]TypeScript generics, constraint for function paramters in object

我想要完成的事情:

假设有一个类型如下的配置:

type ExmapleConfig = {
    A: { Component: (props: { type: "a"; a: number; b: number }) => null };
    B: { Component: (props: { type: "b"; a: string; c: number }) => null };
    C: { Component: () => null };
};

所以,一般来说,形状像这样:

type AdditionalConfigProps = {
    additionalConfigProp?: string;
    // + more additional props that don't have to be optional
};

type ReservedComponentProps = {
    reservedComponentProp: string;
};

type ComponentProps = ReservedComponentProps & Record<string, any>;

type Config = {
    [key: string]: {
        Component: (props: PropsShape) => JSX.Element;
    } & AdditionalConfigProps;
};

我想像这样转换配置,但是:

  • 保留键的硬类型( 'A' | 'B' | 'C'而不是string
  • 保留道具的硬类型( { type: "a"; a: number; b: number }而不是Record<string, any>
  • 确保变换 function 只接受正确的配置,即:
    • 它具有Component属性,以及AdditionalConfigProps中具有正确类型的所有其他属性,
    • 它不会接受定义的ComponentAdditionalConfigProps中的任何其他属性,
    • Component function 必须能够接受ComponentProps -like object 作为第一个参数,

转换可能如下所示:


const config = {
    A: { Component: (props: { type: "a"; a: number; b: number }) => <div>abc</div> };
    B: { Component: (props: { type: "b"; a: string; c: number }) => <div>abc</div>  };
    C: { Component: () => <div>abc</div>  };
};

/*
    Let's say that it will extract Components, and wrap them
    with additional function so void will be returned instead of JSX
*/
const transformedConfig = transformConfig(config);

// typeof transformedConfig
type ResultType = {
    A: (props: { type: "a"; a: number; b: number }) => void;
    B: (props: { type: "b"; a: string; c: number }) => void;
    C: () => void;
};

请注意:

  • 键 'A' 的硬类型 | 'B' | 'C' 被保留
  • 保留了“道具”的硬类型

我尝试过的方法:

import React from "react";

type AdditionalConfigProps = {
    additionalConfigProp?: string;
};

type ReservedComponentProps = {
    reservedComponentProp: string;
};

const CORRECT_CONFIG = {
    A: {
        Component: (props: { type: "a"; a: number; b: number }) => null,
        additionalConfigProp: "abc"
    },
    B: { Component: (props: { type: "b"; a: string; c: number }) => null },
    C: { Component: (props: { reservedComponentProp: "c"; a: string }) => null },
    D: { Component: (props: {}) => null },
    E: { Component: () => null }
};

const BAD_CONFIG = {
    // Missing Component or other required config prop
    A: {},
    // Bad additionalConfigProp
    B: { Component: () => null, additionalConfigProp: 123 },
    // Bad Component
    C: { Component: 123 },
    // Bad component props type
    D: { Component: (props: boolean) => null },
    // Unexpected 'unknownProp'
    E: { Component: () => null, unknownProp: 123 },
    // Bad 'reservedProp'
    F: { Component: (props: { reservedProp: number }) => null }
};

function configParser<
    Keys extends string,
    ComponentPropsMap extends {
        [Key in Keys]: ReservedComponentProps & Record<string, any>;
    }
>(config: {
    [Key in Keys]: {
        Component: (props?: ComponentPropsMap[Keys]) => React.ReactNode;
    } & AdditionalConfigProps;
}) {
    /*
        TODO: Transform config.
        For now we want to make sure that TS is even able to 'see' it correctly.
    */
    return config;
}

/*
    ❌ Throws unexpected type error
*/
const result = configParser(CORRECT_CONFIG);

// Expected typeof result (what I'd want)
type ExpectedResultType = {
    A: {
        Component: (props: { type: "a"; a: number; b: number }) => null;
        additionalConfigProp: "abc";
    };
    B: { Component: (props: { type: "b"; a: string; c: number }) => null };
    C: { Component: (props: { reservedComponentProp: "c"; a: string }) => null };
    D: { Component: (props: {}) => null };
    E: { Component: () => null };
};

/*
    ❌ Should throw type errors, but not the ones it does
*/
configParser(BAD_CONFIG);

当然我可以做这样的事情:

function configParser<
    Config extends {
        [key: string]: {
            Component: (componentProps: any) => React.ReactNode;
        };
    }
>(config: Config) {
    return config;
}

// No type error, result type as expected
const result = configParser(CORRECT_CONFIG);

但它:

  • 不会验证componentProps (也许componentProps: Record<string, any> & ReservedComponentProps会,但由于某种原因它不会接受CORRECT_CONFIG
  • 将允许任何其他配置属性

这是一种可能的方法:

type VerifyConfigElement<T extends AdditionalConfigProps &
{ Component: (props: any) => void }> =
  { [K in Exclude<keyof T, "Component" | keyof AdditionalConfigProps>]: never } &
  {
    Component: (
      props: Parameters<T["Component"]>[0] extends ComponentProps ? any : ComponentProps
    ) => void
  }

declare function transformConfig<
  T extends Record<keyof T, AdditionalConfigProps & { Component: (props: any) => void }>>(
    config: T & { [K in keyof T]: VerifyConfigElement<T[K]> }
  ): { [K in keyof T]: (...args: Parameters<T[K]["Component"]>) => void }

这个想法是:

  • config参数的类型T中使transformConfig()泛型
  • T 约束为一个相对容易编写的类型,它不会拒绝好的输入,在这种情况下,它是AdditionalConfigProps & {Component: (props: any) => void}>
  • 通过将其从自身T[K] 映射到相关类型VerifyConfigElement<T[K]>来更彻底地检查推断T的每个属性,其中T[K] extends VerifyConfigElement<T[K]>当且仅当它是一个好的输入;
  • T计算返回类型,方法是将T的每个属性映射到 function 类型,其参数通过索引到相应的Component属性来确定。

VerifyConfigElement<T>类型检查两件事:

  • T没有在AdditionalConfigProps (或"Component" ,当然)中没有明确提及的任何属性......它通过将任何此类额外属性映射为具有never类型来做到这一点,这几乎肯定会无法进行类型检查;
  • TComponent方法的第一个参数可以分配给ComponentProps ...它通过映射到any如果是这样(这将成功)和ComponentProps如果不是(这可能会失败?function 类型在其输入参数中是逆变的,所以有这里可能是一些边缘情况)。

让我们测试一下:

const config = {
  A: { Component: (props: { type: "a"; a: number; b: number }) => <div>abc</div> },
  B: { Component: (props: { type: "b"; a: string; c: number }) => <div>abc</div> },
  C: { Component: () => <div>abc</div> }
};
// typeof transformedConfig
type ResultType = {
  A: (props: { type: "a"; a: number; b: number }) => void;
  B: (props: { type: "b"; a: string; c: number }) => void;
  C: () => void;
};////
const transformedConfig: ResultType = transformConfig(config);

看起来不错! 对于您的CORRECT_CONFIGBAD_CONFIG ,编译器分别接受和拒绝它们:

const okay = transformConfig(CORRECT_CONFIG); // okay
const bad = transformConfig(BAD_CONFIG); // error

如预期的。

Playground 代码链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM