タイプ互換性

12005 ワード

ケーキまたはサブタイプの場合は、공변を割り当てることができます.
let sub1: 1 = 1;
let sup1: number = sub1; //sub1타입은 sup1타입의 서브 타입이다.

let sub2: number[] = [1];
let sup2: object = sub2;

let sub3 : [number,number] = [1,2]; //튜플 : 길이와 타입이 고정된 배열
let sup3: number[]= sub3;

let sub4: number = 1;
let sup4: any = sub4;
sub4 = sup4; //error가 발생하지 않는다.

let sub5: never = 0 as never;
let sup5: number = sub5;

class Animal {}
class Dog extends Animal {
  eat(){}
}

let sub6:Dog = new Dog();
let sup6:Animal = sub6;

let sub7:string = '';
let sup7:string | number = sub7;

//object 각각의 프로퍼티가 대응하는 프로퍼티와 같거나 서브타입이어야 한다.
let sub8: {a:string;b:number} = {a: '', b:1};
let sup8: {a:string |number; b:number} = sub8;


let sub9: Array<{a:string; b:number}> = [{a:'', b:1}];
let sup9:Array<{a:string|number; b:number}> = sub9;
クラス関数のパラメータタイプが同じかスーパータイプの場合、반병を割り当てることができます.
(strictFunctionTypeオプションで関数を割り当てる場合、関数のパラメータタイプが異なるかスーパータイプでない場合はエラーで警告します.)
class Person{}

class Developer extends Person{
  coding(){}
}
class StartupDeveloper extends Developer{
  burning(){}
}

function tellme(f: (d:Developer) => Developer) {}

tellme(function dToD(d:Developer) : Developer{
  return new Developer();
}) 

tellme(function pToD(d:Person) : Developer { //person이 슈퍼타입인 경우
  return new Developer();
})

tellme(function sToD(d:StartupDeveloper) : Developer {
  return new Developer(); //error발생
})