首页 前端知识 typescript基础用法

typescript基础用法

2024-07-30 22:07:16 前端知识 前端哥 956 250 我要收藏

类型

null undefined boolean void number string symbol bigInt

{} class function []

interface objType {
	name:string
	age:number
}

const arr:string[] = ['a','b'] 

class person {}
const Student:person = new person()

const func:() => string = () => return '' 
const func = ():string => return ''

类型注解和类型推断

类型注解是人为指定变量类型

let count:number = 123
let temp:string | number = '234'

类型推断是ts通过变量值倒推变量类型,但一些复杂类型无法推断

funtion sum(a,b){ return a+b }
如上就无法推断a和b的类型

函数常用写法

有返回值的函数类型指定

functon (count:number,num:number):string{
	return count + num + ''
}

无返回值的函数类型指定

functon (count:number,num:number):void{
	console.log(count+ num)
}

函数无法执行或死循环类型的指定

function err():never { throw new Errow() }
function dea():never { while(true){} }

函数参数为对象结构

function fun({count,num}:{count:number,num:number}):number{
	return count + num
}
const sum = fun({count:10,num:20})

数组和元组的常用写法

基本数组类型的定义

const arr:string = ['2','4']
const arr:(number | string)[] = [1,'2',3]
const arr:undefined[] = [undefined]

对象数组类型的定义

const arr:{name:string,age:number}[] = [{name:"郭",age:21}]
type User = {name:string,age:number}
const arr:User[] = [{name:"郭",age:21}]
class User {name:string,age:number}
const arr:User[] = [new User(),{name:"郭",age:21}]

元组tuple:已知数组长度,并为每个元素进行类型约束

const arr:[string,string,number] = ['郭','男',21]
const arr [string,string,number][] = [
	['郭','男',21],
	['郭','男',21]
]

interface接口

type代表别名,可以直接给类型。接口必须代表对象

type Str = string
interface Person {
    name: string;
    age: number;
}

非必需值 ? ,方法约束

interface Person {
	name:string
	age:number
	hobby?:string
	say():string //say方法的返回值为string
}

任意值 [] any

//接收一个任意的属性名为string类型,值为any类型
interface Person {
	name:string
	[propName:string]:any
}
//所有的属性名都为string类型,值为any类型
interface Person {
	[key:string]:any
}

类和接口的结合 implements

class User implements Person {}

接口的继承 extends

interface Teacher extands Person {}

接口定义函数

interface Say {
	(word:string):string
}
const say:Say = (word) =>{ return '' }

联合类型和保护类型

联合类型

interface Student {
	name:string
	say:()=>{}
}
interface Teacher {
	hobby:string
	skill:()=>{}
}
function judge(person:Student | Teacher){}
//如上person不知道是什么类型,就会出问题,这时候就要引入类型保护 (下边几种)

类型断言 as

function judge(person:Student | Teacher){
	if(person.hobby){
		(person as Teacher).skill()
	}else{
		(person as Student).say()
	}
} 

in

function judge(person:Student | Teacher){
	if('skill' in person){
		person.skill()
	}else{
		person.say()
	}
}

typeof

function add(first:string | number,second:string | number){
	if(typeof first === 'string' || typeof second === 'string'){
		return `${first}${second}`
	}
	return first + second
}

instanceof

class Num{
	count:number
}
function add(first:object | Num,second:object | Num){
	if(first instanceof Num && second instanceof Num){
		return first.count + second.count
	}
	return 0
}

枚举 Enum

enum对应的数字值,默认从0开始。enum可以指定从几开始。也可以为每一项指定值

enum Status {
	OFFINE = 1,
	ONLINE = 4,
	DELETED
}
console.log(Status[4])
//通过下标的方式拿值 结果:ONLINE

泛型 generic

泛型就是传入什么类型返回什么类型

function getData<T,Y>(value:T,grd:Y):T {
	return `${first}${second}`
}
console.log(geData<number,string>(123,'124'))
//传入sring类型的数组
function arr<T>(params:T[]){
	return params
}
function arr<T>(params:Array[]){
	return params
}
arr<string>(['123'])

泛型类

class DataManager<T>{
	constructor(private data:T[]){}
	getItem(index:number):T {
		return this.data[index]
	}
}
//泛型可以继承一个接口,保证该泛型数据内必定要接受接口的约束
interface Item {name:string}
class DataManager<T extends Item>{}

eturn params
}
arr([‘123’])


泛型类

class DataManager{
constructor(private data:T[]){}
getItem(index:number):T {
return this.data[index]
}
}
//泛型可以继承一个接口,保证该泛型数据内必定要接受接口的约束
interface Item {name:string}
class DataManager{}


装饰器(不写了)
转载请注明出处或者链接地址:https://www.qianduange.cn//article/14647.html
标签
评论
发布的文章

AE、Lottie、JSON简单介绍

2024-08-12 10:08:42

VSCode配置settings.json

2024-08-12 10:08:42

JSON 格式说明

2024-08-12 10:08:34

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!