javascript 如何正确推断Typescript中的嵌套和复杂类型?

uoifb46i  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(107)

我认为有时候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;
}
kwvwclae

kwvwclae1#

我认为问题在于你从store返回了什么。
Stored接受一个泛型参数,它应该扩展Storable,但是当在store中返回Stored<T>时,实际上返回的是Stored<MyObject>,而MyObject不会扩展Storable,这就是为什么stored的类型是never
因此,最简单的解决方案是将返回类型更改为Stored<Storable<T, B>>

相关问题