美文网首页简友广场哲思
TypeScript类型兼容性

TypeScript类型兼容性

作者: 不思量q | 来源:发表于2019-11-26 13:44 被阅读0次
/*
 * 类型兼容性,用于确定一个类型是否能赋给另一个类型(避免低级错误)
 TS的类型兼容性基于结构类型,而结构类型是一种只使用其成员来描述类型的方式
 基本规则:如果X要兼容Y,那么Y至少具有与X相同的属性
*/
 class Person3 {
   constructor(public weight: number, public name: string, public birthday: string) {

   }
 }
 interface Dog3 {
   name: string,
   birthday: string
 }
let hashiqi: Dog3
hashiqi = new Person3(12, 'hashiqi', '2019-11-26')
console.log(hashiqi) // Person3 { weight: 12, name: 'hashiqi', birthday: '2019-11-26' }

// 函数类型兼容性
let x = (a: number) => 0
let y = (a: number, b: number) => 0
y = x //OK
// x = y //Error,注意和JS的差别,TS中y先赋给x后依然会报错

// 可选参数,同理,参数数量不一致也会报错
let foo = (x: number, y: number) => {};
let bar = (x?: number, y?: number) => {};
let bas = (...args: number[]) => {};
// 严格检测下报错
// foo = bar = bas;
// bas = bar = foo;

// 枚举的类型兼容性
enum States {
  ready,
  waiting
}
let state = States.ready
let num2 = 2
let str1 = '111'

// state = str1 // string 不兼容
state = num2 
num2 = state // state: 2, num2: 2
console.log(`state: ${state}, num2: ${num2}`)

// 类的类型兼容性
// 仅实例成员和方法会比较,构造函数和静态成员不会被检查
class Animal2 {
  feet: number;
  constructor(name: string, length: number) {

  }
}
class Size2 {
  feet: number;
  constructor(meters: number) {

  }
}

let animal2: Animal2
let size2: Size2

// size2 = animal2 // 非strict模式下均OK
// animal2 = size2

// private&protected成员必须来自相同的类
class Animal3 {
  protected feet: number;
}
class Cat3 extends Animal3 {}

let animal3: Animal3;
let cat3: Cat3;

// animal = cat3; // ok
// cat = animal; // ok
class Size3 {
  protected feet: number;
}

let size3: Size3;

// animal3 = size3; // ERROR
// size3 = animal3; // ERROR

// 泛型的类型兼容性
interface Person4<T> {
  // name: T
}
let x1: Person4<string>
let x2: Person4<number>
// 非严格模式下均OK
// x1 = x2
// x2 = x1

// 如何区分Person5和Animal5?
interface Person5 {
    name: string;
    age: number;
  weight: number;
}

interface Animal5{
    name: string;
    age: number;
  weight: number;
}

function getPersonName(p: Person5) {
  console.log(p)
}

getPersonName({name: 'a', age: 20, weight: 30})

相关文章

网友评论

    本文标题:TypeScript类型兼容性

    本文链接:https://www.haomeiwen.com/subject/tdhewctx.html