TransWikia.com

Why does passing a number when a string is expected not fail compilation

Stack Overflow Asked by Jim Jeffries on December 13, 2021

I have the following code where I am passing a number to a function which takes a string.

const getGreeting: Function = (name: String): String => {
    return `hello, ${name}`;
};

const x: number = 2
console.log(getGreeting(x))

I can understand why the outputted javascript works but why does this not result in a compilation error?

One Answer

It doesnt result to an error because casting your function to Function makes typescript to loose the details of your method.

To make it work, type properly getGreeting like :

playground

const getGreeting: (name: string) => string = (name: string): string => {
    return `hello, ${name}`;
};

const x: number = 2

console.log(getGreeting(x));

Or let typescript to infer the type itself :

playground

const getGreeting = (name: string): string => {
    return `hello, ${name}`;
};

const x: number = 2

console.log(getGreeting(x));

Answered by Orelsanpls on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP