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(); //OK
fn([,,]) //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.

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

  1. [TypeScript] Infer the Return Type of a Generic Function Type Parameter

    When working with conditionals types, within the “extends” expression, we can use the “infer” keywor ...

  2. [TypeScript] Model Alternatives with Discriminated Union Types in TypeScript

    TypeScript’s discriminated union types (aka tagged union types) allow you to model a finite set of a ...

  3. TypeScript & Advanced Types

    TypeScript & Advanced Types https://www.typescriptlang.org/docs/handbook/advanced-types.html#typ ...

  4. [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 ...

  5. TypeScript Basic Types(基本类型)

    在学习TypeScript之前,我们需要先知道怎么才能让TypeScript写的东西正确的运行起来.有两种方式:使用Visual studio 和使用 NodeJs. 这里我选择的是NodeJs来编译 ...

  6. 投票通过,PHP 8 确认引入 Union Types 2.0

    关于是否要在 PHP 8 中引入 Union Types 的投票已于近日结束,投票结果显示有 61 名 PHP 开发组成员投了赞成票,5 名投了反对票. 还留意到鸟哥在投票中投了反对票~) 因此根据投 ...

  7. [TypeScript] Use the JavaScript “in” operator for automatic type inference in TypeScript

    Sometimes we might want to make a function more generic by having it accept a union of different typ ...

  8. 【区分】Typescript 中 interface 和 type

    在接触 ts 相关代码的过程中,总能看到 interface 和 type 的身影.只记得,曾经遇到 type 时不懂查阅过,记得他们很像,相同的功能用哪一个都可以实现.但最近总看到他们,就想深入的了 ...

  9. TypeScript之定义类型 ( type )

    键值对结构的对象 export type ValidationErrors = { [key: string]: any }; 联合类型(union type) export type HttpEve ...

随机推荐

  1. sublime 支持 vue 语法

    具体步骤如下: 1.如果你没安装Package Control,请先安装,安装方法请自行百度.安装OK后,接下来步骤请参考第2步即可. 2.如果你已经安装过Package Control,安装vue高 ...

  2. Redhat Linux下如何使用KVM虚拟机(视频)

    KVM(kernel-basedVirtualMachine)是一个开源的系统虚拟化模块,自Linux2.6.20之后集成在Linux的各个主要发行版本中.它使用Linux自身的调度器进行管理,所以相 ...

  3. [ Java ] [ Eclipse ] 加速 Eclipse 載入速度-轉載

    加速 Eclipse 載入速度-轉載 https://read01.com/NJjNOB.html

  4. pip 更新安装失败解决方法

    python3 -m ensurepip https://stackoverflow.com/questions/28664082/python-no-module-pip-main-error-wh ...

  5. Spring AOP那些学术概念—通知、增强处理连接点(JoinPoint)切面(Aspect)(转)

    1.我所知道的AOP 初看起来,上来就是一大堆的术语,而且还有个拉风的名字,面向切面编程,都说是OOP的一种有益补充等等.一下让你不知所措,心想着:管不得很多人都和我说AOP多难多难.当我看进去以后, ...

  6. oracle多实例的启动与关闭

    Oracle/oracle登录 1.启监听器 lsnrctl start 监听一般不需要动,如果机器重新启动的话需要将监听启动. 查看当前SID:echo $ORACLE_SID 2.启动数据库实例: ...

  7. [Angular & Unit Testing] Testing Component with Store

    When using Ngrx, we need to know how to test the component which has Router injected. Component: imp ...

  8. hdu 1384 Intervals (差分约束)

    /* 给你 n 个区间 [Ai, Bi],要求从每一个区间中至少选出 Ci 个数出来组成一个序列 问:满足上面条件的序列的最短长度是多少? 则对于 不等式 f(b)-f(a)>=c,建立 一条 ...

  9. “此文件来自其他计算机,可能被阻止以帮助保护该计算机” 教你win7解除阻止程序运行怎么操作

    win7 批量解除可执行文件的锁定 "此文件来自其他计算机,可能被阻止以帮助保护该计算机" http://blog.csdn.net/gscsnm/article/details/ ...

  10. Dcloud课程8 开心一刻应用如何实现

    Dcloud课程8 开心一刻应用如何实现 一.总结 一句话总结:app就是远程调用接口获得数据,我们在后台要做的,就是写一个个让页面获得接口的数据.这里用的是公共笑话接口. 1.ajax返回给页面的h ...