递归地应用复杂的泛型类型 [英] Apply a complex generic type recursively

查看:47
本文介绍了递归地应用复杂的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢Nit的答案,我有一个通用类型 NullValuesToOptional ,它生成每个可为空的值变为可选的类型:

Thanks to an answer from Nit, I have a generic type NullValuesToOptional that generates types where each nullable value becomes optional:

type NullValuesToOptional<T> = Omit<T, NullableKeys<T>> & Partial<Pick<T, NullableKeys<T>>>;

type NullableKeys<T> = NonNullable<({
  [K in keyof T]: T[K] extends NonNull<T[K]> ? never : K
})[keyof T]>;

type NonNull<T> = T extends null ? never : T;

有效:

interface A {
  a: string
  b: string | null
}
type B = NullValuesToOptional<A>; // { a: string, b?: string | null }

现在我想使 NullValuesToOptional 递归:

interface C {
  c: string
  d: A | null
  e: A[]
}
type D = NullValuesToOptional<C>;
// { c: string, d?: NullValuesToOptional<A> | null, e: NullValuesToOptional<A>[] }

有可能吗?

推荐答案

更新:包含TS 3.7版本+数组类型

Update: included TS 3.7 version + array types

你的意思是这样吗?

TS 3.7+(数组中的通用类型参数现在可以为 circular ):

TS 3.7+ (generic type arguments in arrays can now be circular):

type RecNullValuesToOptional<T> = T extends Array<any>
  ? Array<RecNullValuesToOptional<T[number]>>
  : T extends object
  ? NullValuesToOptional<{ [K in keyof T]: RecNullValuesToOptional<T[K]> }>
  : T;

<TS 3.7(延迟接口的类型解析是必需的):

< TS 3.7 (a type resolution deferring interface is necessary):

type RecNullValuesToOptional<T> = T extends Array<any>
  ? RecNullValuesToOptionalArray<T[number]>
  : T extends object
  ? NullValuesToOptional<{ [K in keyof T]: RecNullValuesToOptional<T[K]> }>
  : T;

interface RecNullValuesToOptionalArray<T>
  extends Array<RecNullValuesToOptional<T>> {}

游乐场

测试类型:

interface A {
  a: string;
  b: string | null;
}

interface C {
  c: string;
  d: A | null;
  e: A[];
  f: number[] | null;
}

/*
type EFormatted  = {
    c: string;
    e: {
        a: string;
        b?: string | null | undefined;
    }[];
    d?: {
        a: string;
        b?: string | null | undefined;
    } | null | undefined;
    f?: number[] | null | undefined;
}

=> type EFormatted is the "flattened" version of 
type E and used for illustration purposes here;
both types E and EFormatted are equivalent, see also Playground
*/
type E = RecNullValuesToOptional<C>

使用一些数据进行测试:

Test with some data:

const e: E = {
  c: "foo",
  d: { a: "bar", b: "baz" },
  e: [{ a: "bar", b: "qux" }, { a: "quux" }]
};
const e2: E = {
  c: "foo",
  d: { a: "bar", b: "baz" },
  e: [{ b: "qux" }, { a: "quux" }]
}; // error, a missing (jep, that's OK)

这篇关于递归地应用复杂的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆