[英]Apply a complex generic type recursively
Thanks to an answer from Nit, I have a generic type NullValuesToOptional
that generates types where each nullable value becomes optional:感谢 Nit 的回答,我有一个泛型类型
NullValuesToOptional
,它生成每个可空值都变为可选的类型:
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;
It works:有用:
interface A {
a: string
b: string | null
}
type B = NullValuesToOptional<A>; // { a: string, b?: string | null }
Now I would like to make NullValuesToOptional
recursive:现在我想让
NullValuesToOptional
递归:
interface C {
c: string
d: A | null
e: A[]
}
type D = NullValuesToOptional<C>;
// { c: string, d?: NullValuesToOptional<A> | null, e: NullValuesToOptional<A>[] }
Is it possible?可能吗?
Update: included TS 3.7 version + array types更新:包括 TS 3.7 版本 + 数组类型
Do you mean something like this?你的意思是这样的吗?
TS 3.7+ (generic type arguments in arrays can now be circular ): TS 3.7+(arrays 中的通用类型 arguments 现在可以是圆形的):
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 (a type resolution deferring interface is necessary): < TS 3.7(需要类型解析延迟接口):
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>> {}
Test the type:测试类型:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.