Gistlib Logo

gistlib

react generics in typescript

index.ts
// Generic function
function identity<T>(arg: T): T {
    return arg;
}

let result = identity<string>("hello"); // result will be string type

// Generic class
class DataContainer<T> {
    private data: T;

    constructor(initData: T) {
        this.data = initData;
    }

    getData(): T {
        return this.data;
    }
}

let container = new DataContainer<number>(10); // container is of type number
let data = container.getData(); // data will be of type number
471 chars
23 lines

similar typescript code snippets

function that returns object as type of interface if the object parameter matches type literal of interface. in typescript
return type t if param matches value in typescript
how to use the assignwith function from the lodash library in typescript
function that returns unknown input object as type of interface if the object parameter matches type literal of interface. in typescript
a generic function for storing cache into localstorage in typescript
generic function that parses object from string and returns object as matching interface. in typescript
how to use the map function from the lodash library in typescript
how to use the concat function from the lodash library in typescript
split an array of generics into chunks of size n in typescript
store generic into localstorage in typescript

related categories

typescript
generics

gistlibby LogSnag