Some TypeScript types take another type as an argument, written in angle brackets after the name. Array<string> is an array that holds strings, and Array<number> one that holds numbers. Types like these are called generic.
Every command and output on this page is real, run with Node.js 26.13.1 and TypeScript 7.0.2 on macOS.
Syntax
GenericType<TypeArgument>
GenericType: a type that takes a type argument, such asArrayorMap.<TypeArgument>: the type to fill in, in angle brackets. A type that takes two, such asMap<string, number>, takes them separated by a comma.
See Generics (opens in a new tab) in the TypeScript handbook.
Prerequisites
- Node.js 24.12 or later, which runs TypeScript files directly. Install it from the Node.js download page (opens in a new tab).
- TypeScript, for the
tsccommand. Install it withnpm install -g typescript, as the TypeScript download page (opens in a new tab) shows.
The Example
A list of names typed as Array<string>, and a line that tries to add a number to it. The file is names.ts.
Step 1: Write the Code
const names: Array<string> = ["Sam", "Ana"];
names.push(42);
Step 2: Check It with tsc
tsc --noEmit names.ts
names.ts(3,12): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
Array<string> only takes strings, so tsc rejects the number at line 3.
Step 3: Fix It
Add a name instead, and print the list:
const names: Array<string> = ["Sam", "Ana"];
names.push("Lee");
console.log(names);
Step 4: Check It and Run It
Check it again. No output means tsc found no errors:
tsc --noEmit names.ts
Then run it:
node names.ts
[ 'Sam', 'Ana', 'Lee' ]
The list now holds three strings.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out the type argument: Array | tsc reports error TS2314: Generic type 'Array<T>' requires 1 type argument(s). | Fill it in: Array<string> |
FAQ
Is Array<string> the same as string[]?
Yes. The TypeScript handbook’s Everyday Types (opens in a new tab) page says the two mean the same thing.
Conclusion
Fill in a generic type with its type argument in angle brackets, such as Array<string>, and tsc keeps everything else out.
Additional Resources
- Generics (opens in a new tab) (TypeScript handbook)
- Everyday Types (opens in a new tab): arrays (TypeScript handbook)
TypeScript, Node.js and other names mentioned are trademarks of their respective owners.
0 comments