So say there is a type or interface that defines properties of actions, for example:
export interface AnimalActions {
jump: { height: number }
move: { speed: number, offset: number }
}
And there is class that should implement these actions depending on the generic prop, for example:
export class AnimalAction<T extends keyof AnimalActions> {
type: T;
constructor(type: T, actionProps: AnimalActions[T]) {
this.type = type;
Object.assign(this, actionProps);
}
}
const action = new AnimalAction('jump', { height: 10 });
action.type // "jump"
action.height // 10, typescript error here
Playground here, see the error on the last line.
Is there some way to type AnimationAction class so it does not throw an error for height
?
I realize that I can create a third type, for example:
type ExtraAnimalAction<T extends keyof AnimalActions> = AnimalAction<T> & AnimalActions[T];
const action = new AnimalAction('jump', { height: 10 }) as ExtraAnimalAction<'jump'>;
action.type // "jump"
action.height // 10, no error
playground with no error
Is there some way to do this without adding a type?