TS


基础知识

基础类型:number string boolean array object undefined void

  1. enum 枚举
  2. type interface
  3. 联合类型 | (联合类型一次只能用一种类型)
  4. 交叉类型 & (交叉类型每次都是多个类型的合并类型)
  5. typeof 可以用来获取一个变量声明或者对象的类型
function toArray(x:number): Array<number>{
    return [x];
}
type Func = typeof toArray;
  1. keyof 用来获取一个对象中的key
interface Person {
    name:string;
    age:number;
}
type K1  = keyof Person; // 'name'|'age'
  1. in 用来遍历枚举类型
type Keys = 'a'|'b'|'c';

type Obj = {
    [key in Keys]: number;
}
const obj: Obj = {
    a:1,
    b:2,
    c:3
}
  1. extends 用以约束泛型
interface ILengthwise {
    length:number;
}
function loggingIdentity <T extends ILengthwise>(arg:T):T {
    return arg;
}
loggingIdentity({length:10,value:1})
  1. 泛型:类型参数
interface A<T> {
    a:T;
}
const b:A<number> = {a:0}
  1. partial 及 required
    Partial是将必选项变为可选项
    Required是将可选项变为必选项
interface A {
    name:string;
    age:string;
}
// interface B {
//     name?:string;
//     age?:string;
// }

type B = Partial<A>;

type C = Required <B>;
const a:A = {
    name:'',
    age:''
}

常见面试题

  1. 你觉得ts的好处是什么
    1.1 ts是js的加强版,是js超集,给js添加了可选的静态类型或者基于类的面向对象编程,ts的功能比js只多不少
    1.2 ts是面向编程的语言,包含了类、接口的概念
    1.3 ts在开发时就能给出编译错误,js错误只能在运行时体现
    1.4 作为强类型语言,可以明确知道所有数据的类型

  2. type和interface的区别
    用interface来描述数据结构,用type来描述类型,只是写法不同

type setUser = (name:string) => void
interface setUser {
  (name:string): void
}

2.1 相同点
都能用来描述函数和对象
都允许extends
2.2 不同点
type可以有别名,可以声明联合类型,interface不行
type可以声明具体某个数组元素的位置
type可做事情比interface多

type Name = string;
type a = b| c;
type PetList = [Dog, Pet];
  1. 什么是泛型,泛型的具体使用

  2. 如何基于一个已有的类型,扩展出一个大部分内容相似,但是部分区别的类型

interface Test {
  name:string;
  sex:number;
  height:string;
}
type Sex = Pick<TEst,'sex'>;
type WithoutSex = Omit<Test,'sex'>;

实战

实现routerHelper
实现页面倒计时

原理


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM