# 【金秋打卡】第23天 2小时极速入门 TypeScript（3-5）

2022.11.15 20:32 38浏览

## 课程内容：

1、联合（Union）类型；
2、字面量（Literal）类型；

## 课程收获：

1、联合（Union）类型

``````let union string | number
union = 2;
// union = true; 会报错

let union2: number | string | boolean | string[]

function merge(n1: number | string, n2 : number | string) {
if(typeof n1 ==="string" || typeof n2 ==="string")
return n1.toString() + n2.toString();
else
return n1 n2
}

let mergeNumber = merge(2,5)
let mergestring  = merge("hello","world");
console.Log(mergeNumber)
console.log(mergestring)
``````

2、字面量（Literal）类型；

``````// 字面量类型(literal)
let union3: 0 | 1 | 2
union3 = 1
// union3 = 4 会报错

let literal : 1 | "2" | true | [1,2,3,4]
``````

``````function merge(
n1: number | string,
n2: number | string,
resultType: "as-number" | "as-string"
) {
if (resultType === "as-string"){
return n1.toString() + n2.toString();
}
if (typeof n1 ==="string"typeof n2 ==="string")
return n1.toString()+n2.toString();
else return n1 n2;
}

let mergeNumber = merge(2, 5, "as-number")
let mergeNumber2 = merge(2, 5, "as-string")
let mergestring = merge("hello", "world", "as-string");

console.Log(mergeNumber)
console.log(mergeNumber2)
console.log(mergestring)
``````

0人点赞

1

7

### 风间影月说签约讲师

51篇手记，涉及Java、MySQL、Redis、Spring等方向

### Tony Bai 说签约讲师

151篇手记，涉及Go、C、Java、Python等方向

• 推荐
• 评论
• 收藏
• 共同学习，写下你的评论

0/150