一、ts相比js优势
1、更早的发型类型错误
编程语言动静来区分,ts为静态编程语言,js为动态编程语言,静态类型在编译期做检查,动态类型在执行期做检查
2、提高了代码的可维护性
3、任何位置都有代码提示
二、TS中声明对象类型为什么用小写
在 Javascript 中的这些内置构造函数:Number、String、Boolean他们用于创建对象的包装对象,在日常开发时很少使用,在 TypeScript 中也是同理,所以在 TypeScript 中进行类型声明时,通常都是用小写的number、string、boolean。
小写为基本类型对象、大写为包装对象
比如
打印一个字符串通常为
let a='string';
console.log(a)
而不会使用
let n=new String('string')
console.log(n.valueOf())
三、类型总结:
js:
string、number、boolean、null、undefined、symbol、bigint、object(arry、function、Date、Error等)
ts:
上述js所有类型
any(放弃类型检查,可能导致运行时错误)
unknown(表示任意类型,但是使用前需要通过断言确定类型)
never(一般用来定义函数返回值类型如报错等)
void(一般用来定义函数返回值类型(即无函数无返回值的时候使用))
tuple、enum
两个用于自定义类型:type、interface
四、断言
1、尖括号语法:(<类型>):适用于简单类型转换,例如(<string>someValue)将someValue断言为string类型。
2、as语法:(someValue as 类型):推荐使用,与JSX兼容性更好,例如(someValue as string)
3、非空断言:使用!操作符排除null和undefined,例如maybeString!将maybeString断言为非空字符串。
五、索引签名
let person: {
name:string
age:number
key[string]:any
}
person = {
name:'张三',
age:18,
gender:'男'
height:180
}
六、interface
1、定义类结构
interface PersonInterface{
name:string
age:number
run:(n:number)=>void
}
class Person implements PersonInterface {
constructor(
public name:string
public age:number
){}
speak(n:number):void=>{
for(let i =0;i<n;i++){
console.log(`你好我叫${this.name},我的年龄是${this.age}`)
}
}
}
const p1 = new Person('tom',18)
p1.speak(2)
2、定义对象结构
interface UserInterface{
name:string
age:number
run:(n:number)=>void
}
const user:UserInterface = {
name:'张三',
age:18,
run(n)=>{
console.log(`奔跑了${n}米`)
}
}
3、定义函数的结构
interface CountInterface{
(a:number, b:number):number;
}
const count:CountInterface =(x, y)=>{
return x+y
}
4、接口之间的继承
interface PersonInterface {
name:string //姓名
age: number//年龄
}
interface StudentInterface extends PersonInterfa{
grade:string //年级
}
const stu:StudentInterface={
name:'张三'
age:18,
grade:'初二'
}
5、接口自动合并(可重复定义)
interface PersonInterface {
name:string //姓名
age: number//年龄
}
interface PersonInterface{
grade:string //年级
}
const p:StudentInterface={
name:'张三'
age:18,
grade:'初二'
}
总结:何时使用接口
1、定义对象的格式:描述数据模型、api响应格式、配置对象.....等,是开发中用的最多的场景
2、类的契约:规定一个类需要实现那些属性和方法
3、自动合并:一般用于扩展第三方库的类型,这种特性可能在大型项目中用到
七、interface与type
相同点:interface与type都可以定义对象结构,两者在许多场景中可以互换
不同点:
interface更专注于定义对象和类的结构,支持集成、合并
type可以定义类型别名、联合类型、交叉类型、但不支持继承和自动合并
八、泛型
1、泛型函数
function logoData<T,U>(data1:T,data2:U):T|U{
return Data.now() % 2 ? data1 : data2
}
logoData<number, boolean>(10, true)
logoData<string, number>('hello', 20)
2、泛型接口
interface PersonInterface<T>{
name: string
age: number
extraInfo:T
}
type JobInfo ={
title: string;
company: string
}
let p:PersonInterface<JobInfo>={
name: 'tom',
age: 18,
extraInfo:{
title:'高级开发工程师',
company:'发发发科技有限公司'
}
}
3、泛型类
class Person<T>{
constructor(
public name: string,
public age: number,
public extraInfo:T
){}
speak(){
console.log(`我叫${this.name}今年${this.age}岁了)
console.log(this.extraInfo)
}
}
// 测试代码1
const p1 =new Person<number>("tom",30,250);