我认为有时候Typescript在处理复杂和嵌套类型时不能正确地进行推断。
我想知道这是个bug还是我做错了。如果我做错了,实现嵌套和复杂类型推理的最佳方法是什么?
到目前为止,我得到了这样的代码:
// Storable type is the Object with an optional key prop
type Storable<O, Key extends string> = O & { [key in Key]?: string };
// Stored type is the Object with a required key prop
type Stored<S> = S extends Storable<infer O, infer Key extends string> ? O & { [key in Key]: string} : never
// MyObject is a standard object
type MyObject = { prop1: boolean; prop2: number; };
// MyStorableObject is a Storable MyObject
type MyStorableObject = Storable<MyObject, "id">;
// Transforms a Storable object to a Stored object
function store<T, B extends string>(object: Storable<T, B>, key: B): Stored<T> {
return { ...object, [key]: 'generatedId' } as unknown as Stored<T>;
}
当我调用store函数时,我希望storednot永远不会是type:
const storableObject:MyStorableObject = { prop1: true, prop2: 0 };
const stored = store(storableObject, 'id');
奇怪的是,有时候,它工作,有时候它不工作。例如,对于此MyObject类型:
type MyObject = { prop1: string };
存储的对象类型是我所期望的:
const stored: MyObject & {
id?: string | undefined;
} & {
id: string;
prop1: string;
}
1条答案
按热度按时间kwvwclae1#
我认为问题在于你从
store
返回了什么。Stored
接受一个泛型参数,它应该扩展Storable
,但是当在store
中返回Stored<T>
时,实际上返回的是Stored<MyObject>
,而MyObject
不会扩展Storable
,这就是为什么stored
的类型是never
。因此,最简单的解决方案是将返回类型更改为
Stored<Storable<T, B>>