簡體   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