Jarzka
Jarzka

Reputation: 773

Should TypeScript guarantee functions' return value?

I have the following simple function which takes any type of argument and is supposed to return a number:

function foo(x:any): number {
    return x.bar;
}

var b = {bar: "shit happens"};
console.log(foo(b)); // foo returns 'shit happens' which is not a number.

It seems that if x.bar does not contain a number then this function's return value can be anything.

My question is: Is there a way to guarantee that the function's return value will always be a number and nothing else (like in other strongly typed languages)? If not, then what's the advantage of using TypeScript if the typing system only gives a "hint" of the preferable return types that should be used and permits incorrect return types.

Upvotes: 1

Views: 318

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164287

The problem here is your use of the any type.
Basically you're telling the compiler "look, I know what I'm doing, don't check things for me".
You should avoid using any because then you bypass the compiler checks, and if you're going to do that, then why not just use javascript?

If you won't use any but a type or interface then you'll get an error:

type FooParam = {
    bar: number;
}

function foo(x: FooParam): number {
    return x.bar;
}

var b = { bar: "shit happens" };
console.log(foo(b));

(code in playground)

You'll get an error in the last line:

Argument of type { bar: string; } is not assignable to parameter of type { bar: number; }

You can avoid having this FooParam type:

function foo(x: { bar: number }): number { ... }

Upvotes: 4

Related Questions