Learn
TypeScript can also infer the types of values returned by functions. It does this by looking at the types of the values after a function’s return
statements.
function createGreeting(name: string) { return `Hello, ${name}!`; } const myGreeting = createGreeting('Aisle Nevertell');
Here’s how TypeScript can infer myGreeting
above to be of type string
:
createGreeting()
’sreturn
statement is followed by astring
variable, socreateGreeting()
is inferred to returnstring
.createGreeting('Aisle Nevertell')
therefore must result in a value of typestring
.myGreeting
is initialized tocreateGreeting('Aisle Nevertell')
, which is a value with the typestring
.
Cool! Let’s see how this can help us fix bugs:
function ouncesToCups(ounces: number) { return `${ounces / 16} cups`; } const liquidAmount: number = ouncesToCups(3); // Type 'string' is not assignable to type 'number'.
Here, TypeScript was able to infer that liquidAmount
was being assigned a value of type string
, despite it being declared as a variable of type number
. This correctly results in an error being surfaced.
Instructions
1.
Challenge! Using what you’ve learned above, create a variable myVar
with the type number
. To make this more interesting:
- You must not use the
:
character. - You must not type any numbers into your code.
- You may not use functions other than the one provided in index.ts.
Take this course for free
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.