【typescript】 Typescript字面量类型 、 Typescript字面量类型使用模式和场景

 一.Typescript字面量类型

let num1 = 'hello'

const num2 = 'hello'

答案:

num1 类型为 string , num2类型为 ‘hello’

描述: 

1.num1 是一个变量 let , 他可以是任意的字符串 所有类型为 string

2.num2是一个常量 ocnst , 他的值不能变量只能是 'hello' ,所以类型是 'hello'

注意: 这里 cosnt 声明的  'hello' 就是字面量类型 ,某个特定的字符串可以作为 ts中的类型

二.Typescript字面量类型使用模式和场景

type mytype = 'up' | 'down' | 'left' | 'right'

function numtion (event: mytype  ) {

console.log(event)

}

numtion('up')

描述: 实参只能传 'up' | 'down' | 'left' | 'right' 内任意一个 , 形参已经定义类型

优势: 相比 string 类型 ,使用字面量类型更加准确 严谨


 

猜你喜欢

转载自blog.csdn.net/m0_64494670/article/details/129269659
今日推荐