繁体   English   中英

在 Typescript 类型中有一个可选的第二个参数

[英]Have a optional second parameter in Typescript type

我有这两种非常相似的类型:

import { VariantProps } from "@stitches/core";

export type VariantOption<
  Component extends { [key: symbol | string]: any },
  VariantName extends keyof VariantProps<Component>
> = Extract<VariantProps<Component>[VariantName], string>;

export type Variants<
  Component extends { [key: symbol | string]: any }
> = Extract<VariantProps<Component>, string>;

从这里可以看出,它们都非常相似,唯一的区别是第二种类型不采用第二个泛型参数,因此它不采用VariantProps<Component>类型的索引。

是否可以将它们两者合并,使第二个参数是可选的,并根据未设置的结果更改结果?

它会是这样的(无效的语法):

import { VariantProps } from "@stitches/core";

export type VariantOption<
  Component extends { [key: symbol | string]: any },
  VariantName? extends keyof VariantProps<Component>
> = VariantName ?
        Extract<VariantProps<Component>[VariantName], string> :
        Extract<VariantProps<Component>, string>;

您可以像这样为泛型设置“默认”值:

type Foo<X extends string, Y extends object = {baz: string}> = {
    xParam: X;
    yParam: Y;
}

在您的情况下,它将类似于VariantName extends keyof VariantProps<Component> = ??? 在哪里 ??? 是您想要的默认类型。

根据您所需的用例,您可以更花哨地使用条件类型来“根据未设置的结果更改结果”,如您所说:

// yParam is "null" if second generic type is not specificed
type Foo<X extends string, Y extends object | unknown = unknown> = {
    xParam: X;
    yParam: Y extends object ? Y : null;
}

type Bar = Foo<'hello', {}>;
/*
type Bar = {
    xParam: "hello";
    yParam: {};
}
*/

type Baz = Foo<'world'>;
/*
type Baz = {
    xParam: "world";
    yParam: null;
}
*/

编辑:如果我根据您的问题了解您想要的行为,这可能会起作用:

export type VariantOption<
  Component extends { [key: symbol | string]: any },
  VariantName extends keyof VariantProps<Component> | unknown = unknown
> = VariantName extends keyof VariantProps<Component>
  ? Extract<VariantProps<Component>[VariantName], string>
  : Extract<VariantProps<Component>, string>;

暂无
暂无

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

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