我正在try 编写一个函数,该函数接受一个描述符对象,并使用推断的类型信息返回一个不同的对象,该对象具有一个具有强类型的良好API.
我遇到的问题是,如果嵌套属性被限制为联合类型,则TypeScrip似乎只能推断它们的类型.如果它们被限制为基元类型(例如string
),则它们将保持该基元类型,而不会缩小到传入的实际文字.
type ChildType = 'foo' | 'bar' | 'baz';
type ChildDescriptor<
TName extends string = string,
TType extends ChildType = ChildType,
> = {
name: TName;
type: TType;
};
type ParentDescriptor<
TSomeProp extends string,
TChildren extends ChildDescriptor[],
> = {
someProp: TSomeProp;
children: [...TChildren];
};
// Identity function so we can observe what types are inferred
const identity = <
TSomeProp extends string,
TChildren extends ChildDescriptor[],
>(
descriptor: ParentDescriptor<TSomeProp, TChildren>,
) => descriptor;
const inferredValue = identity({
someProp: 'I get inferred',
children: [
{
name: 'I don\'t get inferred',
type: 'foo',
},
{
name: 'I don\'t get inferred either',
type: 'baz',
}
],
});
const [childA, childB] = inferredValue.children;
在上面的示例中,inferredValue
的children
属性被正确地推断为元组,并且子对象的someProp
属性和type
属性被缩小到我想要的特定文本类型.但是,子对象的name
属性保持为string
的类型,我不知道为什么.
我可以通过在每个没有缩小范围的值之后添加as const
来解决这个问题,或者甚至在每个子对象之后添加它.由于元组的原因,它不能工作在比这更低的嵌套级别,它变成只读的,然后很难在带有泛型的API中使用它.在任何情况下,我都希望完全避免这种解决方案,因为添加类型断言感觉像是一种黑客行为,而不是真正的解决方案.
最后,这些描述符对象将使用我将构建的另一款软件生成,因此,如果有必要,我将使用解决方法.我只是想看看有没有其他我看不到的解决方案.
我正在工作的环境被限制在TypeScrip 4.7.4,所以我必须坚持使用该版本中提供的功能.