Gibb Sonn
Gibb Sonn

Reputation: 459

is there a way go get typescript to detect when i'm returning undefined from function?

I was hoping that typescript maybe able to detect when a function could return an undefined value and warn me. I tried the following but the playground editor on typescript site did not show any warnings

class Test {

    get(key: string) :string{

        var hash = {'some-key': 1, 'some-other-key': 3};

        return hash[key]

    }    

}

Is it possible to get typescript to warn when a function could sometimes return a undefined value when you explicitly stated that it should only return some particular type?

Upvotes: 3

Views: 1288

Answers (3)

Fenton
Fenton

Reputation: 250922

TypeScript doesn't check the existence of the property when you use hash[key] as it would when you use hash.myKey. So to get design-time and compile-time checking you would have to change the way you expose this information to allow the code to use the dot-property syntax...

So instead of:

class Test {
    get(key: string) :string{
        var hash = {'some-key': 1, 'some-other-key': 3};
        return hash[key];
    }    
}

var test = new Test();
test.get('myKey');

You could expose:

class Test {
    public hash = { someKey: 1, someOtherKey: 3};
}

var test = new Test();
test.hash.myKey; // you'll get a warning here

This only works if this design is appropriate for what you are doing - but you'll get the warnings doing things this way as TypeScript will create an anonymous type for hash and will ensure only known properties are used.

Update: I updated the examples based on feedback. It is worth noting that although using 'some-key' prevents you from using dot-notation (so it is definitely worth dropping the hyphen if you can) - you will still get code-completion.

Upvotes: 2

basarat
basarat

Reputation: 275867

As Steve mentioned you can use property access (.) instead of index access ([string]). But that will work only if your properties follow typescript naming conventions. i.e. property names cannot contain '-' e.g. the following works:

class Test {
    public hash = {'someKey': 1, 'someOtherKey': 3};
}

var test = new Test();
test.hash.someKey;// Valid
test.hash.myKey; // you'll get a warning here

Upvotes: 0

Alex Dresko
Alex Dresko

Reputation: 5203

It might not stop you from accidentally returning undefined, but your code definitely returns undefined as proven by:

class Test {

    get(key: string) :string{

        var hash = {'some-key': 1, 'some-other-key': 3};

        return hash[key]

    }    

}

var test = new Test();
alert(test.get("asdf"));

TypeScript would need to support something like CodeContracts to do what you are asking.

Upvotes: 0

Related Questions