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

posted @   Zhentiw  阅读(633)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-10-06 [Reactive Programming] Async requests and responses in RxJS
点击右上角即可分享
微信分享提示