[Typescript] Introduction to Generics in Typescript

If Typescript is the first language in which you‘ve encountered generics, the concept can be quite difficult to understand. We skip the lecture in this lesson and dive straight into a real-world use-case that is guaranteed to help you understand the need for generics.

Let‘s say we have this part of code:

class Emitter{
    emit(event){
        console.log(event);
    }
}

const emitter = new Emitter();

emitter.emit({path: ‘/home‘, directory: true});

The object we want to pass in is {path: "", directory: ""}. But it may happen that we have some typo error, so we want IDE helps us to detect that.

TO do this, we need interface:

class Emitter<MyEvent>{
    emit(event: MyEvent){
        console.log(event);
    }
}

interface MyEvent{
    path: string
    directory: boolean
}

const emitter = new Emitter<MyEvent>();

emitter.emit({path: ‘/home‘, directory: true});

So it defines that the emit() function‘s param should have ‘directory‘ and ‘path‘ attrs. If not, it will report error.

So far so good, but what happen if we have anyother function inside the class, such as:

class Emitter<T>{ // T: allow everything come in
    emit(event: MyEvent){
        console.log(event);
    }

    yield(value: MyValue){
        console.log(value);
    }
}

interface MyEvent{
    path: string
    directory: boolean
}

interface MyValue{
    message: string
}

const emitter = new Emitter<MyEvent>();
const yielder = new Emitter<MyValue>();

emitter.emit({path: ‘/home‘, directory: true});
yielder.yield({message: "Hello World!"});

yield() take objet with message prop, and the interface defined as MyValue. So allows Emitter class accept multi interfaces, we can use <T>, then for each function, we add the interface for that.

时间: 2024-07-31 14:22:24

[Typescript] Introduction to Generics in Typescript的相关文章

[TypeScript] The Basics of Generics in TypeScript

It can be painful to write the same function repeatedly with different types. Typescript generics allow us to write 1 function and maintain whatever type(s) our function is given. This lesson covers syntax and a basic use case for Typescript generics

[TypeScript] Understand lookup types in TypeScript

Lookup types, introduced in TypeScript 2.1, allow us to dynamically create types based on the property keys of an object. We'll use the function spyOn from Jest to illustrate how lookup types can type-safe function parameters. Considering this code:

[TypeScript] Overload a Function with TypeScript’s Overload Signatures

Some functions may have different return types depending on the types of the arguments with which they’re invoked. Using TypeScript’s function overloads, you can create an overload for each allowed combination of parameter and return types. This way,

[Typescript] Specify Exact Values with TypeScript’s Literal Types

A literal type is a type that represents exactly one value, e.g. one specific string or number. You can combine literal types with union types to model a finite set of valid values for a variable. In this lesson, we explore the all kinds of literal t

[TypeScript] Represent Non-Primitive Types with TypeScript’s object Type

ypeScript 2.2 introduced the object, a type that represents any non-primitive type. It can be used to more accurately type methods such as Object.create. Don't confuse it with the Object type or {}, the empty object type, though! Type 'Object' gives

TypeScript手册翻译系列7-泛型

泛型(Generics) 软件工程的一个主要部分是建立不仅有良好定义和一致性APIs,而且是可重用的组件(components).使用今天数据以及明日数据的组件才能够最为灵活地构建大规模软件系统. 在类似C#和Java等语言中,工具箱中创建可重用组件的一个主要工具就是泛型(generics),即能够创建可以使用各种类型而不是单一类型的组件.这使得用户可以用自己的类型来调用这些组件. Hello World of Generics 我们先来做一个泛型的"hello world":iden

使用TypeScript拓展你自己的VSCode

转自:http://www.iplaysoft.com/brackets.html使用TypeScript拓展你自己的VSCode! 0x00 前言在前几天的美国纽约,微软举行了Connect(); //2015大会.通过这次大会,我们可以很高兴的看到微软的确变得更加开放也更加务实了.当然,会上放出了不少新产品和新功能,其中就包括了VS Code的beta版本.而且微软更进一步,已经在github将VS Code的代码开源了.除了这些让人兴奋的消息,我们还应该注意到VS Code提供了对拓展的支

TypeScript和JavaScript哪种语言更先进

TypeScript和JavaScript哪种语言更先进 近两年来最火爆的技术栈毫无争议的是JavaScript,随着ES6的普及,不管是从前端的浏览器来看,还是后端的NodeJS场景,JavaScript技术栈不断的向世界证明自己的价值.JavaScript代码越写越大,众所周知,JavaScript是一门动态语言,缺少静态类型检查,这样就很难在编译阶段排除更多的问题,当然,这就是动态语言的魅力所在,运行时动态处理类型,在我们写代码的时候就可以很更灵活.为了给JavaScript增加类型检查以

[TypeScript] Catch unsafe use of &quot;this&quot; in TypeScript functions

this is probably the most tricky thing to use in JavaScript and therefore TypeScript. Fortunately there is a TypeScript compiler flag noImplicit this that can help catch unsafe usages so beginners don't get caught off guard. // tsconfig.json { "compi