Nils Luxton
Nils Luxton

Reputation: 766

Is it possible to add type information at compile time?

Let's say I have the following code:

function addProperties(keys: String[]): Object
{
    // For the sake of example, this is a concrete return
    return {
        firstProperty: "first_value",
        secondProperty: "second_value"
    };
}

export default {

    propertyBag: {
        ...addProperties(["firstProperty", "secondProperty"])
    },

    someMethod() {
        return this.firstProperty;
    }

};

Typescript naturally complains that firstProperty does not exist on this object.

Is it possible to 'dynamically' add the type information to let TS know that both firstProperty and secondProperty exist on this object?

Ideally I'd like to be able to do this without having to have a separate definition for propertyBag, as suggested in the answer below.

Upvotes: 1

Views: 38

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

Not sure where addProperty comes from and what the definition of that is, but assuming that it returns an object with the properties specified as parameters, you can specify that someMethod will have a this parameter that is the same type as the property bag. The only catch is you need to separate the definition of the propertyBag from the export default:

const propertyBag = {
    ...addProperties(["firstProperty", "secondProperty"])
};
export default {
    propertyBag,
    someMethod(this: typeof propertyBag) {
        return this.firstProperty;
    }
};

// Assumed definition 
function addProperties<T extends string>(a: T[]) : { [P in T]: any} {
    return null as any;
}

Upvotes: 1

Related Questions