[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(); //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的更多相关文章
- [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 ...
 - [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 ...
 - TypeScript & Advanced Types
		
TypeScript & Advanced Types https://www.typescriptlang.org/docs/handbook/advanced-types.html#typ ...
 - [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 ...
 - TypeScript  Basic Types(基本类型)
		
在学习TypeScript之前,我们需要先知道怎么才能让TypeScript写的东西正确的运行起来.有两种方式:使用Visual studio 和使用 NodeJs. 这里我选择的是NodeJs来编译 ...
 - 投票通过,PHP 8 确认引入 Union Types 2.0
		
关于是否要在 PHP 8 中引入 Union Types 的投票已于近日结束,投票结果显示有 61 名 PHP 开发组成员投了赞成票,5 名投了反对票. 还留意到鸟哥在投票中投了反对票~) 因此根据投 ...
 - [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 ...
 - 【区分】Typescript 中 interface 和 type
		
在接触 ts 相关代码的过程中,总能看到 interface 和 type 的身影.只记得,曾经遇到 type 时不懂查阅过,记得他们很像,相同的功能用哪一个都可以实现.但最近总看到他们,就想深入的了 ...
 - TypeScript之定义类型 ( type )
		
键值对结构的对象 export type ValidationErrors = { [key: string]: any }; 联合类型(union type) export type HttpEve ...
 
随机推荐
- Day2上午解题报告
			
预计分数:100+0+60=160 实际分数:100+0+60=160 mmpT1数据错了... T1遭遇 题目描述 你是能看到第一题的 friends呢. —— hja ?座楼房,立于城中 . 第? ...
 - Kinect 开发 —— 面部识别
			
EmguCV库也能用来进行面部识别(face identify).实际的面部识别,就是将一张图像上的人物的脸部识别出来,这是个很复杂的过程,具体过程我们这里不讨论.对一幅影像进行处理来找到包含脸部的那 ...
 - STANDBY REDO LOG
			
SRL Introduce 从">ORACLE9i开始,出现了Standby Redo Logs(SRL),9.1开始只有">physical standby支持SRL ...
 - Eclipse怎样把文件系统形式的项目作为工程直接导入?
			
导入的时候,选择已经存在的工程,如果选择文件系统,可能会提示没有项目可以导入.这个时候,可以从其它Eclipse项目下,copy一份.project文件过来,修改源文件中的工程名字.如果需要,也可以c ...
 - [NOI.AC#41]最短路 线性基
			
链接 题解 如果不加边,两个点之间的长度是唯一的(只能走最短路径),因为如果重复走,就异或掉了. 因此,先DFS预处理一下每个点到根的距离 \(d[x]\) ,那么 \(x,y\) 之间的距离为 $d ...
 - 3.JPA开发
			
转自:https://blog.csdn.net/aspnetandjava/article/details/7034779 1. 什么是JPA 1. JPA(Java Persistence API ...
 - Linux下PortSentry的配置
			
Linux下PortSentry的配置 前年写过<IDS与IPS功能分析>一文,受到广大读者关注,现将近期有关IDS配置的文章和大家分享. Internet上的服务器一般 ...
 - 用C#生成随机中文汉字验证码的基本原理
			
前几天去申请免费QQ号码,突然发现申请表单中的验证码内容换成了中文,这叫真叫我大跌眼镜感到好笑,Moper上的猫儿们都大骂腾讯采用中文验证码.^_^ 我不得不佩服腾讯为了防止目前网络上横行的QQ号码 ...
 - js全选反选按钮实现
			
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
 - Vue简介以及基本使用
			
Vue 是一套构建用户界面的渐进式 框架 框架和库? 框架(基于自身的特点向用户提供一套完整的解决方案,控制权在框架本身,需要使用者按照框架所规定的某种规范进行开发) Vue Angular Reac ...