阿里云主机折上折
  • 微信号
Current Site:Index > Basic concepts of generics

Basic concepts of generics

Author:Chuan Chen 阅读数:46288人阅读 分类: TypeScript

What Are Generics

Generics are a powerful feature in programming languages that allow defining functions, interfaces, or classes without specifying the concrete type in advance, but instead specifying it when used. Generics in TypeScript provide a balance between code reuse and type safety. With generics, you can create reusable components that support multiple types without sacrificing type checking.

function identity<T>(arg: T): T {
    return arg;
}

let output1 = identity<string>("hello");
let output2 = identity<number>(42);

Generic Variables

Inside a generic function, the type variable T represents any type. The compiler requires that these generic variables be used correctly. When using generics to create structures like arrays, TypeScript knows about the existence of array methods.

function loggingIdentity<T>(arg: T[]): T[] {
    console.log(arg.length);
    return arg;
}

function loggingIdentity2<T>(arg: Array<T>): Array<T> {
    console.log(arg.length);
    return arg;
}

Generic Types

The type of a generic function is no different from that of a non-generic function, except that it has a type parameter listed first. You can use different generic parameter names as long as the quantity and usage correspond.

let myIdentity: <T>(arg: T) => T = identity;
let myIdentity2: <U>(arg: U) => U = identity;

interface GenericIdentityFn {
    <T>(arg: T): T;
}

let myIdentity3: GenericIdentityFn = identity;

Generic Classes

Generic classes look similar to generic interfaces. Generic classes use angle brackets <> to enclose the generic type, placed after the class name. Classes have two parts: the static part and the instance part. Generic classes refer to the type of the instance part.

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

let stringNumeric = new GenericNumber<string>();
stringNumeric.zeroValue = "";
stringNumeric.add = function(x, y) { return x + y; };

Generic Constraints

Sometimes you need to restrict the range of types for a generic. In such cases, you can use the extends keyword to implement generic constraints. Define an interface to describe the constraint and then have the generic type extend this interface.

interface Lengthwise {
    length: number;
}

function loggingIdentity3<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);
    return arg;
}

loggingIdentity3(3);  // Error: number doesn't have a .length property
loggingIdentity3({length: 10, value: 3}); // Correct

Using Type Parameters in Generic Constraints

A type parameter can be constrained by another type parameter. For example, if you want to get a property from an object using the property name and ensure the property exists on the object.

function getProperty<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];
}

let x = { a: 1, b: 2, c: 3, d: 4 };

getProperty(x, "a"); // Correct
getProperty(x, "m"); // Error: m is not a key of x

Using Class Types in Generics

When using generics to create factory functions in TypeScript, you need to reference the class type of the constructor. The relationship between the constructor and the class instance is inferred and constrained through the prototype property.

class BeeKeeper {
    hasMask: boolean;
}

class ZooKeeper {
    nametag: string;
}

class Animal {
    numLegs: number;
}

class Bee extends Animal {
    keeper: BeeKeeper;
}

class Lion extends Animal {
    keeper: ZooKeeper;
}

function createInstance<A extends Animal>(c: new () => A): A {
    return new c();
}

createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:模块最佳实践

下一篇:泛型函数定义

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.