Is there a TypeScript compiler option to force type checks on object properties?

Viewed 2417

In order to write more robust code, I'm looking at using TypeScript for my web based projects. I have relatively little experience with the language thus far, but I have run into a problem that I'm having difficulty searching for.

Consider the TypeScript code below:

public static getResponseCode(resObj: object): number {
    let c: number = resObj["c"]
    return c;
}

Is there a way that I can force the TypeScript compiler to pull me up here and tell me that resObj["c"] may not be a number and that I need to first check if it is a number? E.g. can I force TypeScript to make me rewrite the code as this (or something similar)?:

public static getResponseCode(resObj: object): number {
    if (typeof resObj["c"] !== "number") { return APIResponseCode.UnknownFailure; }

    let c: number = resObj["c"]
    return c;
}

I expect I'm getting the results that I am simply because the type of resObj["c"] is any. What can I do here? Is there a common pattern used in TypeScript?

2 Answers
Related