Skip to main content
0 reactions

How to Pass a Type Argument to a Generic Type in TypeScript

A card titled Generic Type Arguments, labelled TypeScript Basics, showing an Array of string rejecting push(42) with TS2345 and accepting push(“Lee”), for 3 strings.
Generic Type Arguments: Fill in a type such as an Array of strings.

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

SyntaxTypeScript
GenericType<TypeArgument>
  • GenericType: a type that takes a type argument, such as Array or Map.
  • <TypeArgument>: the type to fill in, in angle brackets. A type that takes two, such as Map<string, number>, takes them separated by a comma.

See Generics (opens in a new tab) in the TypeScript handbook.

Prerequisites

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

names.tsTypeScript
const names: Array<string> = ["Sam", "Ana"];

names.push(42);

Step 2: Check It with tsc

TerminalBash
tsc --noEmit names.ts
OutputPlain text
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:

names.tsTypeScript
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:

TerminalBash
tsc --noEmit names.ts

Then run it:

TerminalBash
node names.ts
OutputPlain text
[ 'Sam', 'Ana', 'Lee' ]

The list now holds three strings.

Common Mistakes

MistakeWhat happensDo this instead
Leaving out the type argument: Arraytsc 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

TypeScript, Node.js and other names mentioned are trademarks of their respective owners.

0 comments