我想通过Generics使开发人员定义的对象类型安全,以避免属性中的拼写错误.接口可以通过属性相互交叉引用,有时作为特定类型的一维array.null
标记嵌套的最后一个元素,但这是我任意 Select 的.
该 struct 可以按照开发人员想要的深度进行嵌套,并且应该只允许高级属性类型的类型的属性-但并非所有属性都这样做,有些是数字、字符串等.
这是基本的接口 struct ,其中有一个示例(expander
):
interface Base {
id: string;
}
interface Foo extends Base {
name: string;
subFoo: Foo;
bars: Bar[];
}
interface Bar extends Base {
description: string;
foo: Foo;
}
const expander: Expander<Bar> = {
foo: null, // correct
foo: { bars: { foo: null } }, // correct
foo: { baz: null }, // should error b/c baz is not a property of Foo
baz: null, // should error b/c baz is not a property of Bar
};
到目前为止,我try 的是:
type BaseOrArray = Base | Base[];
type Expander<B extends BaseOrArray> = {
[P in keyof B]: B[P] extends BaseOrArray ? Expander<B[P]> | null : never;
}[keyof B];
但这给了我一个错误:
属性"bars"的类型在映射类型"{ [P in keyof Foo]:Foo[P]扩展了Base OrArray?扩展器<Foo[P]>|空:从不;}'.