[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 ...
随机推荐
- sql server 内置MD5加密函数
http://blog.csdn.net/rookie_liu_ToFly/article/details/53116932 select right(sys.fn_VarBinToHexStr(HA ...
- xml格式报文的拼装,和解析成实体类
我们的微信支付,使用的是第三方的支付,某银行的微信支持渠道.所有的接口请求.应答都是xml格式报文,这样就需要用到xml格式报文的拼装和解析,这儿简单讲一下. 拼接xml格式报文. 从页面表单提交和配 ...
- Android之——短信的备份与还原
转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47091281 眼下,Android手机中的一些软件能够实现手机短信的备份与还原操作 ...
- oracle 10g standby database 实时应用 redo 数据
-------physical standby database: real-time apply 须要配置 standby redo log: 启用实时应用, 日志应用服务会直接应用接收的redo ...
- js23---工厂模式1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...
- 关于Webpack详述系列文章 (第二篇)
1.缩小文件搜索范围 1.1.1 include & exclude module:{ rules:[ { test:/\.js$/, use:['babel-loader?cacheDire ...
- Vue Invalid handler for event "": got undefined
原因:绑定的方法不是放在methods:{}里.比如我把绑定的函数写在了computed:{}里就会报这个错.
- HDU4825 Xor Sum(贪心+Trie树)
Problem Description Zeus 和 Prometheus 做了一个游戏,Prometheus 给 Zeus 一个集合,集合中包含了N个正整数,随后 Prometheus 将向 Zeu ...
- echarts如何设置背景图的颜色
公司的业务涉及到统计图的有很多,最近一直echarts里面踩各种坑,感觉应该建立一个echarts专题才对,前端的东西博大精深,无论在哪一个知识点,只要细细深究,都是别有一方天地在等待,随着需求的不同 ...
- listctrl调整表头高度
CListCtrl派生类下CMyListCtrl.h class CMyListCtrl :public CListCtrl { public: // 设置表头高度 void SetHeadHeigh ...