typescript字面量类型

typescript 字面量介绍

在TypeScript中,字面量是指在代码中直接使用的具体值,如字符串、数字、布尔值等。字面量类型是TypeScript中的一种特殊类型,它用于定义一组有限的值,并且可以在定义变量或函数时使用字面量作为具体值,也可以作为类型的一部分限定变量或函数的取值范围。

示例如下

let str1 = 'hello world'
const str2 = 'hello world'

typescript字面量类型_第1张图片
上面的代码通过ts类型推论机制,我们可以看到,两个变量类型是不同的

  1. str1的变量类型是:string
  2. str2的变量类型是:‘hello world’

这是因为str1是一个变量,(let)可以是任意的string类型数据,额,可以是任意类型字符串,所以变量类型是string
而str2是一个常量(const) 它的值不能发生变化,所以只能是’hello world’,所以它的类型为’hello world’

也就是说,此处的’hello world’就是一个字面量类型,
某个特定的字符串可以作为ts中的类型, 如下

let str1 = 'hello world'
const str2 = 'hello world'
//将hello world作为类型
let str3: 'hello world' = 'hello world'

当然,除了字符串外,任意的js字面量都能当作类型使用

let str1 = 'hello world'
const str2 = 'hello world'

let str3: 'hello world' = 'hello world'

let age: 18 = 18
let isChild: [1, 2] = [1, 2]

搭配联合类型使用

在 TypeScript 中,联合类型(Union Types)是一种特殊的数据类型,它允许一个值具有多种类型中的一种。字面量(Literal)则是表示固定值的语法。可以通过字面量搭配联合类型来定义一个变量,使其只能具有指定的值之一。

示例如下

// 定义一个类型为 "apple" | "banana" 的字面量  
type Fruit = "apple" | "banana";  
  
// 定义一个变量,其类型为 Fruit,并赋值为 "apple"  
let myFruit: Fruit = "apple";  
  
// 试图将变量赋值为非法值,将会导致编译错误  
// myFruit = "orange"; // Type '"orange"' is not assignable to type 'Fruit'  
  
// 可以使用 switch 语句来进行类型检查  
function checkFruit(fruit: Fruit) {  
  switch (fruit) {  
    case "apple":  
      console.log("It's an apple.");  
      break;  
    case "banana":  
      console.log("It's a banana.");  
      break;  
    // 如果没有匹配的值,将会导致编译错误  
    // default: // This condition will never be met. Its type 'never' is not assignable to type 'Fruit'  
  }  
}  
  
checkFruit(myFruit); // 输出 "It's an apple."

当然也可以为函数的参数限定值,比如,如果是一个游戏人行走的函数,那么这个函数应该只接收上下左右四个类型的参数
示例如下

首先,需要创建一个联合类型,该类型可以是 “上”、“下”、“左” 或 “右”。在 TypeScript 中,使用 type 关键字来定义类型,然后使用 | 运算符来创建联合类型。

type Direction = "上" | "下" | "左" | "右";

接下来,定义一个函数,该函数接收一个 Direction 类型的参数:

function move(direction: Direction) {  
    switch (direction) {  
        case "上":  
            console.log("角色向上移动");  
            break;  
        case "下":  
            console.log("角色向下移动");  
            break;  
        case "左":  
            console.log("角色向左移动");  
            break;  
        case "右":  
            console.log("角色向右移动");  
            break;  
    }  
}

然后,就可以像这样调用这个函数:

move("上"); // 输出 "角色向上移动"  
move("下"); // 输出 "角色向下移动"  
move("左"); // 输出 "角色向左移动"  
move("右"); // 输出 "角色向右移动"

当试图传递一个不是 “上”、“下”、“左” 或 “右” 的参数给 move 函数,TypeScript 编译器将会抛出一个错误:

move("前"); // 错误:参数不能赋值给 'Direction' 类型

你可能感兴趣的:(typescript,typescript,ubuntu,javascript,ts字面量类型,typescript字面量类型,字面量类型详解,typescript字面量详解)