美文网首页typescript学习笔记
typescript学习笔记-基础类型

typescript学习笔记-基础类型

作者: daoqing99 | 来源:发表于2022-09-18 09:15 被阅读0次

基础类型快速入门

基础类型 string,number,boolean
const teacher:string = 'Li';
const age:number = 18;
const isMale:boolean = true;
数组类型 string,number,boolean
const arr:number[] = [1,2,3]  // 数字类型数组
const arr:string[] = [1,2,3]   // 字符串类型数组
const boolArr:Array<boolean> = [true,false]  // 传参形式定义布尔数组,范型
对象类型
const user:{name:string,age:number} = {name:'Li',age:18}
const userOne:{name:string,age?:number} = {name:'Li'}  // ?表示age可有可无
联合类型 Union Type |
function union(id:string|number){
  if (typeof id === 'string') {  // 类型收窄 Narrowing
      console.log(id.toUpperCase())
  } else {
      consle.log(id)
  }
}
any类型
function showMessage(msg:any){
  console.log(msg)
}
函数类型
function fn(msg:string):number { // 返回值number类型
  return 123
}

const def:(age:number) => number = (age:number) => { return 18}
类型别名,类型复用
type:User = {name:string,age:number}
type:Employee = {name:string,age:number,salary:number}
const userTwo:User = {name:'Li',age:18}
const userThree:User = {name:'Li',age:18}
接口类型 Interface
interface Student {
  age:number;
  sex?:string;
}
// 写法1
interface Student {
  name: string
}
// 写法2
interface oldStudent extends Student {
  name: string
}
const student:Student = {age:18,sex:'male'}
const oldStudent:oldStudent= {age:18,sex:'male',name:'Li'}

interface 类型跟类型别名类似,区别在于。接口类型具有可扩展性可以继承,一般都是尽量用interface

交叉类型
type:User = {name:string,age:number}
type:Employee = User && {salary:number} // 交叉类型

const employee: Employee = {name:"Li",age:18,salary:1000}
断言 Assersion(绕过ts检测,按我们的意思来)
const dom:undefind = document.getElementById('root') as undefind
const dom1:undefind = <undefind>document.getElementById('root') 
const testString:string = 123 as any as string
字面量类型
const str:'abc' = 'abc'  // 只能类型,值一样
function getPosition(position:'left' | 'right') { // 传参只能是left或者 right
  return position
}
getPosition('left')
getPosition('right')
null undefind tsconfig
const testNull:null = undefind // ts不严谨  需配置 `"strictNullChecks": true`
const testundefind:undefind = null // ts不严谨  需配置 `"strictNullChecks": true`
function checkNull(abc:string | null){
  if (typeof abc === 'string') {
      console.log(abc!.toUpperCase()) // !表示可以确定只会是string类型,不会有null
  }
}
void 函数没有返回值
function getNumber():void{

}

相关文章

网友评论

    本文标题:typescript学习笔记-基础类型

    本文链接:https://www.haomeiwen.com/subject/txnsortx.html