[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 ...
随机推荐
- css3--根据数据加载显示的一个动画
css: .circle { width: 200px; height: 200px; position: absolute; border-radius: 50%; background: #0cc ...
- ThinkPad E431 获取无限网络的驱动
sudo apt-get install linux-headers-generic build-essential dkms sudo apt-get install linux-source ...
- UVALive 6527 Counting ones dfs(水
题目链接:点击打开链接 #include <cstdio> #include <vector> using namespace std; typedef long long l ...
- 【吴节操点评】中国企业SaaS应用深谙未来者寥寥数几 两极分化将加剧
数年前,在国外企业级应用如火如荼的时候.国内却是一片空白.而现在企业SaaS应用市场,包含用友.金蝶.东软在内的三巨头.已经有数十家之多.相比美国3000亿美元的企业应用三巨头来说,中国企业应用前三甲 ...
- 前6名免费DNS服务 - 公共DNS服务
前6名免费DNS服务 - 公共DNS服务 谷歌 8.8.8.8,8.8.4.4备份,用户将期望并获得高可用性,如DNSSEC等过滤和安全保护. OpenDNS 现在是Cisco帝国的一部分,主要是20 ...
- weblogic12
http://www.oracle.com/technetwork/middleware/weblogic/downloads/index.html 建立ejb http://docs.oracle. ...
- iTOP-4412开发板使用
使用环境:win7 旗舰64位,VMware11 使用使用板上提供的ubuntu12.04,用VMWARE直接打开虚拟机,因为之前开发epc9600开发板,所以虚拟机网络已经设置过,加载ubuntu1 ...
- numpy_basic
一.Numpy是什么 Numerical Python,数值的Python,补充了Python语言所欠缺的数值计算能力. Numpy是其它数据分析及机器学习库的底层库. Numpy完全标准C语言实现, ...
- ListView-divider 分割线的设置
1.去掉分割线 android:divider="@null" 2.设置分割线颜色跟宽度 android:divider="#19000000" android ...
- java list 容器的ConcurrentModificationException
java中的很多容器在遍历的同时进行修改里面的元素都会ConcurrentModificationException,包括多线程情况和单线程的情况.多线程的情况就用说了,单线程出现这个异常一般是遍历( ...