

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Arrays
incomplete
2: Type Parameters
incomplete
3: Heterogeneous Arrays
incomplete
4: Rest Parameters
incomplete
5: Evolving Any
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
When you create a new empty array, TypeScript infers it as any[].
let inventory = [];
// inventory: any[]
If you then push a type into it, TypeScript will infer the array as that type.
inventory.push(42);
// inventory: number[]
Where it gets weird is that you're actually still allowed to push other types into the array, it just keeps updating the underlying type:
inventory.push("robe");
// inventory: (number | string)[]
This is so fascinating because if we had explicitly typed the array as number[], we would have gotten an error when trying to push a string into it.
let inventory: number[] = [];
inventory.push("robe");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'
The "evolving any" is a special type inference feature. It's not very useful if you're trying to restrict what can be pushed into an array within the initial scope, but it is useful outside of that scope. Let me show you what I mean. Let's say I make a function like this:
function getConfig() {
let config = [];
// config: any[]
config.push("api-key");
// config: string[]
config.push(8080);
// config: (string | number)[]
return config;
}
Within getConfig, the array feels like any... I can just keep adding stuff. However, when I use getConfig:
let config = getConfig();
// config: (string | number)[]
config.push(false);
// Error: Argument of type 'boolean' is not assignable to parameter of type 'string | number'
Now I get an error! The evolving any stops evolving when it's passed around.
Support.ai is collecting data about customer interactions as a performance metric.
Complete the collectSupportData function. It takes an id number and resolved boolean and returns a static array:
"Support session started" stringid numberresolved booleanStart with an empty array, and push each value into it before returning it.
Hover the inferred return type of the collectSupportData function when you're done!