Reputation: 16607
I'm trying to implement a prop update method where the properties and their types are known. The problem I'm running into is that TypeScript will (obviously) not validate the types in a dynamic method.
Is there a way to rewrite this code so any update to the property will be type-checked?
The only thing that comes to my mind is to have a method for each property, like setTitle(), or setVersion() or (maybe) using setters. I wonder if there is a more elegant solution.
interface Props {
title: string
version: number
[key: string]: any // This shouldn't really be here, although otherwise this wouldn't compile. I realize it's only because of this TypeScript allows updating properties dynamically
}
class MyApp {
private props : Props;
constructor() {
this.props = {
title: 'Untitled',
version: 1,
}
}
public updateProp(prop : string, value : any) {
this.props[prop] = value;
this.processUpdate();
}
private processUpdate() {
// do stuff
}
}
let myApp = new MyApp();
myApp.updateProp('title', 10); // just done something improper
Upvotes: 2
Views: 106
Reputation: 5524
You mean something like this:
public updateProp<T extends keyof Props>(prop : T, value : Props[T]) {
this.props[prop] = value;
this.processUpdate();
}
myApp.updateProp('title', 'asd'); // ok
myApp.updateProp('title', 1); // not ok
myApp.updateProp('title', new Date()); // not ok
Upvotes: 3