Maciej Kravchyk
Maciej Kravchyk

Reputation: 16607

TypeScript - handle types in dynamic property updates

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

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgApQPYAcDOyDeAUMicmMGADYQBcyOYUoA5saQG7Q7AYh0gBXALYAjaGxIBtANYQAnnQZMQzALp04IOYQC+hQgkpwceALJyAgliwF9pZFibs4kB5lzI66bDgDcd0gReJQEEMAwoAAoASlsJezIAC2AcADpHH2QAXlsEvLIKajoAcgBVcEKIABNigBp4-OROKG5eOgBGesa9eJ77LAERSmAEZAEsKpcIbyxIjJtFRhZaprhKARQNLViiRrBktPmcSXnVbNX1iH89g-TMJBNSiamY69I+0kdgZ1cMh5wnpNIDFcvkAPRg5BVDD0MACGAwXr6HrUMDIISWaznEAQADuyHMVlm0X8hAxRNS4yB03ckWK5CoEDqyHaAAYScgIcgAFYCBhQ3goHAYIQQfYsZDAITzcSEIA

Upvotes: 2

Views: 106

Answers (1)

zhuber
zhuber

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

Related Questions