[TypeScript] Union Types and Type Aliases in TypeScript

Sometimes we want our function arguments to be able to accept more than 1 type; e.g. a string or an array. This lesson will show us how to assign more than 1 type to a variable with Typescript union types and type aliases.

type types = string | boolean | number;

var fn = (sm: types) => sm;

fn("something"); //OK
fn(false); //OK
fn(10); //OK
fn([2,2,3]) //Error

Union Type:

var fn = (sm: string | boolean | number) => sm;

But it took many places, so to make it shorter, we use Typoe aliases:

type types = string | boolean | number;

var fn = (sm: types) => sm;

‘typeof‘ and ‘instanceof‘:

type types = string | boolean | number | string[];
var fn2 = (something: types) => {
    if(typeof something === "string"
    || typeof something === "boolean"
    || typeof something === "number"){
        console.log(something);
    }

    if(something instanceof Array){
        let str = "";
        something.forEach(s => {
            str += s;
        })
    }
}

Using ‘isntaceof‘, so Typescript understand ‘something‘ is Array type, it will pop up the methods which array can use for.

If we use put unit type as "string" or "object" and try to access the object prop, will throw error:

type stuff = string |{name: string}
var fn3 = (something: stuff) => {
    console.log(something.name) //  compile error
}

If we put tow object in unit type, but they don‘t share the same prop:

type objs = {age: number} | {name: string};
var fn4 = (something: objs) => {
    console.log(something.age); // compile error
    console.log(something.name); // compile error
}

Last if the unit types are objects and share the same prop:

type sharePropObjs = {name: string, age: number} | {name: string, address: string};
var fn4 = (something: sharePropObjs) => {
    console.log(something.age); // compile error
    console.log(something.address); // compile error
    console.log(something.name); // OK
}

To review, the Union type is defined by adding an Or pipe. The Type alias is kind of like a bar, except you‘re defining a type, not a variable. As of now, we have Type of and Instance of for type cards. Type cards let us differentiate between types and allow TypeScript to know what those types are.

If you Union type Objects with Not Objects, the compiler gets mad. If you Union type Objects without a common parameter, the compiler gets mad. If you Union type Objects with a common parameter, you can access that common parameter.

时间: 2024-11-15 05:16:06

[TypeScript] Union Types and Type Aliases in TypeScript的相关文章

[TypeScript] Use the never type to avoid code with dead ends using TypeScript

Example 1: A never stop while loop return a never type. function run(): never { while(true){ let foo = "bar"; } } Example 2: Never run If block const foo = 123; if(foo !== 123) { let bar: never = foo; } You can use this to do exhaustive checks i

TypeScript Basic Types(基本类型)

在学习TypeScript之前,我们需要先知道怎么才能让TypeScript写的东西正确的运行起来.有两种方式:使用Visual studio 和使用 NodeJs. 这里我选择的是NodeJs来编译TypeScript,因为我笔记本上的VS是2012的,在TypeScript的官网看到下载是TypeScript for VS2013和TypeScript for VS2015.额,顺带贴上TypeScript的官网,有需要的去下载. 然后使用NodeJs编译TypeScript的方法: //

[TypeScript] Generic Functions, class, Type Inference and Generics

Generic Fucntion: For example we have a set of data and an function: interface HasName { name: string; } const heros: HasName[] = [ {name: 'Jno'}, {name: 'Miw'}, {name: 'Ggr'}, {name: 'Gew'}, {name: 'Wfe'} ]; function cloneArray(ary: any[]): any[] {

[TypeScript] Define a function type

type DigitValidator = (char) => boolean; const numericValidator = (char) => /[0-9]{1}/.test(char); export const digitValidators: {[key: string]: DigitValidator} = { '9': numericValidator }; We can use 'type' keyword to define a function type. 'digit

[TypeScript] Create Explicit and Readable Type Declarations with TypeScript mapped Type Modifiers

Using the optional “+” sign together with mapped type modifiers, we can create more explicit and readable type declarations. We can also use the “-” (minus) sign to remove optional declarations from properties. For example, we have an interface: inte

[TypeScript] Catch unsafe use of "this" 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

[TypeScript] Sharing Class Behavior with Inheritance in TypeScript

Typescript classes make inheritance much easier to write and understand. In this lesson we look into how to set up inheritance with Typescript classes, extends and super. class ComicBookCharacter ( constructor{ public alias: string, public health: nu

Java中的Union Types和Intersection Types

前言 Union Type和Intersection Type都是将多个类型结合起来的一个等价的"类型",它们并非是实际存在的类型. Union Type Union type(联合类型)使用比特或运算符|进行构造: A | B | C 注意:用|符号来构造Union Type类型只是Java语言的规定,|在这里不代表比特或的含义. 上例中,A | B | C是一个Union type,Union type的含义就是"或",只要满足其中一个即可. 实例:捕获多个异常

c++primer学习笔记(1)-primitive buit-in types and type conversions

1.关于 unsigned 的注意事项: 1.unsigned int 可以缩写成 unsigned 2.当用到char类型时,char 有3种形势,char, signed char 和unsigned char , 当我们写char 时,编译器会从signed char 和unsigned char 中选一种.signed char 是 -127 ~ 127, unsigned char 是0 ~ 255 3. 一定不要将unsigned int 类型和signed int 类型进行运算,应