There seems to be an issue with Typescript not properly inferring complex and nested types at times.
I'm trying to figure out if this is a bug or if there's a mistake on my end. And if it's a mistake on my end, what is the most effective way to achieve inference of nested and complex types?
Here's the code I've come up with so far:
// Defining the Storable type as an Object with an optional key prop
type Storable<O, Key extends string> = O & { [key in Key]?: string };
// Defining the Stored type as an 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 version of MyObject
type MyStorableObject = Storable<MyObject, "id">;
// Function to transform 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>;
}
When I use the store function, I expect the stored object to not be of type "never":
const storableObject: MyStorableObject = { prop1: true, prop2: 0 };
const stored = store(storableObject, 'id');
It's strange that sometimes it works and sometimes it doesn't. For example, with this MyObject type:
type MyObject = { prop1: string };
The stored object type is as expected:
const stored: MyObject & {
id?: string | undefined;
} & {
id: string;
prop1: string;
}