TypeScript-第二章类型

本文介绍了TypeScript中的一些基础概念,包括修改tsconfig.json配置以改变编译源文件的位置,类型系统如数组、泛型、any类型及其带来的类型安全问题,函数的类型定义,对象的类型约束,联合类型以及如何处理,类型别名和接口的使用,类型断言确保类型安全,文字类型限制函数参数,null和undefined的处理,以及枚举、symbol和bigint的数据类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、修改tsconfig.json文件的配置让文件在src路径下编译

"rootDir": "./src",  

"outDir": "./dist",  

2、数组 

let arr:number[] = [1,2,3]//type []

// arr = ['a','b']//报错

let arr2:Array<number> = [1,2,3]//泛型定义

arr2 = [1]

3、any没有进行任何的类型检查

let obj:any = {

  x:0

}

obj.foo()//在ts文件下没有报错

obj()//在ts文件下没有报错

obj.bar = 100//在ts文件下没有报错

obj = 'hello'//在ts文件下没有报错

const n:number = obj//在ts文件下没有报错

 但是在node运行js文件时报错,没有foo这个方法就会报错

删掉any就把它当做对象obj这样ts文件就报错了

4、函数

如果没有定义name类型,它隐式的类型就是any

 如果不指定返回值类型,根据return 返回值类型就可以了 可以省略:number

即使我们没有给s指定类型,ts也能推断出s的类型

 

5、对象

function printCoord(pt:{x:number,y:number}){
  console.log('坐标x的值为'+pt.x);
  console.log('坐标y的值为'+pt.y);
}
printCoord({
  x:3,
  y:7
})
// ?代表可以不传
function printName(obj:{first:string,last?:string}){
  // 调用的时候如果没有?会报错
  console.log(obj.last?.toUpperCase);
}
printName({
  first:'string'
})
printName({
  first:'stirng',
  last:'123'
})

6、联合类型

// 联合类型可以使类型变得更宽,但是使用的时候注意限制条件
function printId(id:string|number){
  // console.log('your id is ' + id);
  // console.log(id.toUpperCase());//报错,因为有可能id是数字,不能转换成大写字符串
  // 解决办法,if判断
  if(typeof id==='string'){
    console.log(id.toUpperCase());
  }else{
    console.log(id);
    
  }
}
printId(100)
printId('1000')
// printId({
//   myId:123455//报错,因为没有定义对象类型
// })

function welcomePeople(x:string[]|string){
  // console.log('hello, ' + x.join());//报错了 因为如果是单纯string没有join方法,只有数组才有
  // 解决方法 加判断
  if(Array.isArray(x)){
    console.log('hello, ' + x.join());
  }else{
    console.log('welcom'+x);
    
  }
}
welcomePeople('string')
welcomePeople(['string','a'])

// slice方法既在数组里又在字符串里
function getFirstThree(x:number[]|string){
  return x.slice(0.3)
}
console.log(getFirstThree('abcdefghijklmnopqrstuvwsyz'));

 7、类型别名-定义变量类型方法

type Point = {
  x:number,
  y:number
}

function printCoord1(pt:Point){

}
printCoord({
  x:200,
  y:300
})

type ID = string | number
function printId1(id:ID){

}
printId(100)
printId('100')

8、接口-定义变量类型方法

interface point1 {
  x:number,
  y:number
}

function printCoord2(pt:point1){

}
printCoord2({
  x:100,
  y:200
})

// 扩展接口
// interface Animal {
//   name:string
// }
// interface Bear extends Animal {
//   honey:boolean
// }
// const bear:Bear = {
//   name:'winie',
//   honey:true
// }
// console.log(bear.name);
// console.log(bear.honey);

// 使用类型别名拓展的方法 加上&符号
type Animal = {
  name:string
}
type Bear = Animal & {
  honey:boolean
}
const bear:Bear = {
  name:'winie',
  honey:true
}
console.log(bear.name);
console.log(bear.honey);

// 向现有的类型添加字段
interface myWindow {
  count:number
}
interface myWindow {
  title:string
}
const w:myWindow = {
  count:100,
  title:'100'
}

// 类型别名这种向现有的类型添加字段不能和接口一样使用相同名字,会报错

9、类型断言

不知道某个变量是什么类型,我们可以把它断言为一个差不多的类型而不是用any,这样就失去了使用ts的意义

const myCanvas = document.getElementById('main_canvas') as HTMLCanvasElement
const myCanvas1 =<HTMLCanvasElement> document.getElementById('main_canvas')
// 防止不可能的强制发生
const x = ('hello' as any) as number//使用any或者unknown
// const y = 'dk' as number//报错

 10、文字类型

function handleRequest(url:string,method:'get'|'post'|'guess'){

}
const req = {
  url:'http://www.baidu.com',
  method:'get'
} as const //解决方法2
// handleRequest(req.url,req.method)//报错
// 解决方法1
handleRequest(req.url,req.method as 'get')

 11、null和undefined类型

let x1:undefined = undefined
let y1:null = null
// let z1:string = undefined

function doSomething(x:string|null){
  if(x===null){
    //做一些操作
  }else{
    console.log('hello '+x.toUpperCase());
    
  }
}
// 可以在不进行任何显示检查的情况下,从类型中删除,叹号在表达式之后,实际上是写入一种类型推断,
// 也就是说这个值不是null或者是undefined的了。
function liveDangerously(x?:number|null){
  console.log(x!.toFixed());
  
}

12、枚举

定义了枚举之后,返回的按照顺序递增

enum Direction {
  Up = 1,
  Down,
  Left,
  Right
}

console.log(Direction.Up);
console.log(Direction.Down);
console.log(Direction.Left);
console.log(Direction.Right);

13、symbol和bigint 

 

const oneHundred:bigint = BigInt(100)//报错
const anotherHundred:bigint = 100n//报错

const firstName = Symbol('name')
const secondName = Symbol('name')
if(firstName===secondName){//报错
  console.log('ok');
  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值