Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Generics

TypeScript Generics

Generics are a programming language feature that allows the use of placeholders to represent types instead of concrete types when defining functions, classes, interfaces, and so on.

Generics are a very useful feature for writing reusable, flexible, and type-safe code.

The main purpose of using generics is to handle data of non-specific types, allowing code to apply to multiple data types without losing type checking.

The advantages of generics include:

Generic identifiers

In generics, some conventional identifiers are commonly used, such as the frequent T(representing Type),U、V , but in fact you can use any identifier.

T: stands for "Type" and is the most common generic type parameter name.

function identity(arg: T): T {

    return arg;

}

K, V: generic type parameters representing Key and Value.



interface KeyValuePair {

    key: K;

    value: V;

}

E: a generic type parameter representing an array element.



function printArray(arr: E[]): void {

    arr.forEach(item => console.log(item));

}

R: a generic type parameter representing a function's return value.

function getResult(value: R): R {

    return value;

}

U, V: commonly used to represent the second and third generic type parameters.



function combine(first: U, second: V): string {

    return `${first} ${second}`;

}

These identifiers are conventional; in fact you can choose any name that follows identifier rules. The key is to make code readable and easy to understand, so it's recommended to use descriptive names for generic type parameters to clarify their purpose.

Generic Functions

Use generics to create a function that can handle different types:

Example

function

identity

<

T

(

arg

:

T

)

:

T

{

   

return

arg

;

}

// Using a generic function

let result

=

identity

<

string

(

"Hello"

)

;

console.

log

(

result

)

;

// Output: Hello

let numberResult

=

identity

<

number

(

42

)

;

console.

log

(

numberResult

)

;

// Output: 42

Analysis: In the above example,identity is a generic function that uses to represent the generic type. It accepts a parameter arg and a return value that are both of the generic type T. When using it, you can explicitly specify the generic type with angle brackets <> . The first call specifies the string type, and the second call specifies the number type.

2. Generic Interfaces

You can use generics to define interfaces so that their members can use arbitrary types:

Example

// Basic syntax

interface

Pair

<

T

,

U

{

first

:

T

;

    second

:

U

;

}

// Using a generic interface

let pair

:

Pair

<

string

,

number

=

{

first

:

"hello"

,

second

:

42

}

;

console.

log

(

pair

)

;

// Output: { first: 'hello', second: 42 }

Analysis: Here a generic interface is defined Pairwith two type parameters T and U. Then, using this generic interface, an object is created pair, where first is of string type,second and is of number type.

3. Generic Classes

Generics can also be applied to a class's instance variables and methods:

Example

// Basic syntax

class

Box

<

T

{

    private value

:

T

;

    constructor

(

value

:

T

)

{

       

this

.

value

=

value

;

   

}

    getValue

(

)

:

T

{

       

return

this

.

value

;

   

}

}

// Using a generic class

let stringBox

=

new

Box

<

string

(

"TypeScript"

)

;

console.

log

(

stringBox.

getValue

(

)

)

;

// Output: TypeScript

Analysis: In this example,Box is a generic class that uses to represent the generic type. Both the constructor and methods can use the generic type T. By instantiating Box, we create a Box instance that stores strings, and retrieve the stored value through the getValue method.

4. Generic Constraints

Sometimes you want to limit the range of a generic's types; you can use generic constraints:

Example

// Basic syntax

interface

Lengthwise

{

    length

:

number

;

}

function

logLength

<

T

extends

Lengthwise

(

arg

:

T

)

:

void

{

    console.

log

(

arg.

length

)

;

}

// Correct usage

logLength

(

"hello"

)

;

// Output: 5

// Incorrect usage, because numbers have no length property

logLength

(

42

)

;

// Error

Analysis: In this example, a generic function is defined logLengththat accepts a parameter of type T , but with a constraint that T must implement the Lengthwise interface, which requires a length property. Therefore, it is correct to call logLength("hello"), but not logLength(42), because numbers have no length attribute.

5. Generics and default values

You can set default values for generics so that a default type is used when no type argument is specified:

Example

// Basic syntax

function

defaultValue

<

T

=

string

(

arg

:

T

)

:

T

{

   

return

arg

;

}

// Using a generic function with a default value

let result1

=

defaultValue

(

"hello"

)

;

// Inferred as string type

let result2

=

defaultValue

(

42

)

;

     

// Inferred as number type

Explanation: This example shows a generic function with a default value. The function defaultValue accepts a generic parameter T, with a default type set to string. When using it, if no type is explicitly specified, the default type is used. In the example, in the first call result1 is inferred as string type, and in the second call result2 is inferred as number type.