It's difficult for me to formulate the title well, let me show you what I want to achieve. First the types:
interface Entity {
id: number;
name: string | null;
}
class EntityDto {
id: number;
name: string | null;
constructor(entity: Entity) {
this.id = entity.id;
this.name = entity.name;
}
}
There will be many classes like EntityDto (ie, UserDto). Later, I need to "unpack" the original object from the dto, like this:
function unpackEntity(dto: EntityDto): Entity {
// logic for creating an Entity object
}
There is clear relationship between the dto and the returned object for all functions like this. I want typescript to infer the return type based on the dto passed.
I know how to get the object type based on class:
type ConstructorArgument<T> = T extends new (...args: infer P) => any ? P[0] : never;
for example:
type ThisIsEntity = ConstructorArgument<typeof EntityDto>
I want to create a type for the "unpacker" function, like so:
type UnpackDto = <TDto>(dto: TDto) => ConstructorArgument<TDto>
So that I can create:
const unpackEntity: UnpackDto = (dto: EntityDto) => {
// ... logic
}
const entity = unpackEntity(entityDto) // correctly has type of Entity
I can't figure out how to make typescript do what I want