Course contentsShow
← TypeScript
Lesson 105 of 1,7963. Basic TypesFree lesson

Typed Array Literals

How TypeScript infers array types from literal values and when inference works automatically.

Typed Array Literals

What you'll learn: How TypeScript automatically figures out what type of array you've created just by looking at the values inside it.

Arrays Know Their Contents

When you write an array literal in TypeScript—values inside square brackets like [1, 2, 3]—TypeScript looks at those values and infers the array's type automatically. You don't need to tell it explicitly; it's smart enough to figure it out.

If all values are numbers, TypeScript infers number[]. If they're all strings, you get string[]. Mixed values? TypeScript creates a union type array that can hold any of those types.

const ages = [25, 30, 42];
// TypeScript infers: number[]

const names = ["Alice", "Bob", "Charlie"];
// TypeScript infers: string[]

const mixed = [1, "hello", true];
// TypeScript infers: (number | string | boolean)[]

When Inference Works Automatically

Inference happens instantly when you initialize an array. TypeScript examines every element in the literal and determines the most specific type that fits all of them. This works whether you use const or let for the variable.

Empty arrays are a special case—TypeScript infers any[] initially because there's nothing to learn from. It then evolves the type as you add elements (though this behavior depends on your compiler settings).

const empty = [];
// Inferred as: any[]

Key Takeaway: TypeScript infers array types from the values you provide in array literals, giving you type safety without extra annotations—but only when there are actual values to learn from.