TS知识点

11 阅读3分钟

一、基础类型

type 和 interface 区别?

核心区别

特性interfacetype
定义范围只能定义对象类型可定义任意类型
声明合并✅ 支持❌ 不支持
继承extends 继承交叉类型 &
映射类型❌ 不支持✅ 支持
联合/元组❌ 不支持✅ 支持
implements✅ 支持✅ 支持
### 1. 定义范围
        // type 可以定义任意类型 
        type ID = string; // 基础类型 
        type Union = string | number; // 联合类型 
        type Tuple = [string, number]; // 元组 
        type Fn = (x: string) => void; // 函数 
        // interface 只能定义对象/函数签名 i
        nterface User { 
            name: string; 
            age: number;
        } 
        interface Fn2 {
           (x: string): void; // 函数签名
        }
 ### 2. 声明合并
    // interface 支持合并(扩展第三方类型时有用) 
    interface User { 
      name: string; 
    } 
   interface User {
      age: number; 
   } 
   // User = { name: string; age: number } 
   
   
   // type 不支持合并,会报错 
   type User = { name: string }; 
   type User = { age: number }; // ❌ 重复标识符
### 3. 继承方式
   // interface 用 extends 
   interface Animal { name: string }
   interface Dog extends Animal { breed: string } 
   
   // type 用交叉类型
   type Animal = { name: string } 
   type Dog = Animal & { breed: string } 
   // interface 继承 type 
   type Base = { id: string } 
   interface Item extends Base { name: string }
### 4. 映射类型
   // type 支持映射类型 
    type Readonly<T> = { readonly [K in keyof T]: T[K] }; 
    type Partial<T> = { [K in keyof T]?: T[K] }; 
    type Pick<T, K extends keyof T> = { [P in K]: T[P] }; 
    
   // interface 不支持 
   interface Readonly<T> { readonly [K in keyof T]: T[K]; // ❌ 语法错误 }
   
### 5. 联合类型 & 元组
   // type 支持
   type Status = 'pending' | 'success' | 'error'; 
   type Point = [number, number]; 
   
   // interface 不支持 
   interface Status = 'pending' | 'success'; // ❌ 语法错误
摘要介绍:注:Object方式: 一切皆对象(Object)。Object是用来定义object.prototype里的类型的,而不是定义对象的.所以不推荐使用Object来定义类型。但是使用了也不会报错。
eg:const piont:Object = {x: '1', y: '2'};(不推荐使用Object来定义类型。但是使用了也不会报错)

那应该用什么来定义呢?➡️ object

const piont:object = {x: '1', y: '2'};

顶端类型(any/unknow)
const obj:object = 'h1'; // 报错 对应1的解释
let obj: object,
obj = Symbol();  //new Date();obj = [0]; 都可进行复制,一切皆对象


const a: any = obj;
const obj2: {} = obj; //对应1、的区别

  1. object方式类型的兼容性: 准确地表示非原始类型,原始类型不允许赋值给object类型。 区别:Object类型是用来描述所有对象共享的属性和方法,也可以进行赋值空对象类型字面量:{}
  2. object类型来表示非原始类型。object类型使用object关键字来标识,注意object全部都是小写。
  3. object类型关注点在于类型的分类上,并不是在该对象上有哪些方法和属性。所以不允许你去读取或者修改类型上的自定义属性,只能访问对象上的公共属性和方法。
  4. 顶端类型为any、unknow;object也可以赋值给any/unknow。(所有类型都是顶端类型的自类型)

对象定义类型-对象类型字面量 Object类型是用来描述所有对象共享的属性和方法,自动封箱 object就是用来表示原始数据类型,不可以对自定义类型进行操作。 {x: numbber, y: number}===>对象类型字面量

1、?可选属性
        const point:{x: number,y: bumber, z?: number}; // 可选模式下,可选属性可以被忽略
        pont = {x: 1, y:1}
2、允许多余属性存在 (as)
    类型断言 as