interface
オブジェクトのみのタイプエイリアス オブジェクトのみにしか使わないのでわかりやすい(絶対にオブジェクトを示していることがわかる)基本
オブジェクトにしか使えないinterface Human {
name: string;
age: number;
}
const human: Human = {
name: 'masaki',
age: 28,
};
オブジェクトの配列
3パターン書いたが、すべて同じオブジェクトの配列を表すexport interface IState {
people: {
name: string;
age: number;
img: string;
note?: string;
}[];
}
const humans: IState['people'] = [
{
name: 'LeBron James',
age: 35,
img: 'https://cdn.nba.com/headshots/nba/latest/1040x760/2544.png',
note: 'Allegeric to staying on the same team',
},
{
name: 'Kobe Bryant',
age: 42,
img: 'https://fullpresscoverage.com/wp-content/uploads/2020/01/101524695-457220551.jpg',
},
];
interface people {
name: string;
age: number;
img: string;
note?: string;
}
const humans: people[] = [
{
name: 'LeBron James',
age: 35,
img: 'https://cdn.nba.com/headshots/nba/latest/1040x760/2544.png',
note: 'Allegeric to staying on the same team',
},
{
name: 'Kobe Bryant',
age: 42,
img: 'https://fullpresscoverage.com/wp-content/uploads/2020/01/101524695-457220551.jpg',
},
];
interface people {
name: string;
age: number;
img: string;
note?: string;
}
const humans: Array<people> = [
{
name: 'LeBron James',
age: 35,
img: 'https://cdn.nba.com/headshots/nba/latest/1040x760/2544.png',
note: 'Allegeric to staying on the same team',
},
{
name: 'Kobe Bryant',
age: 42,
img: 'https://fullpresscoverage.com/wp-content/uploads/2020/01/101524695-457220551.jpg',
},
];
メソッドに適応
interface Human {
name: string;
age: number;
greeting(message: string): void;
}
const human: Human = {
name: 'masaki',
age: 28,
greeting(message: string) {
console.log(message);
},
};
4:implements
インターフェースに存在するメンバーと同じ名前のメンバーが必ず存在している必要がある Humanを満たしていないといけないinterface Human {
name: string;
age: number;
greeting(message: string): void;
}
class Developer implements Human {
constructor(public name: string, public age: number) {}
greeting(message: string) {
console.log('hello');
}
}
readonly
普通にかける publicとprivateは書けないinterface Human {
readonly name: string;
age: number;
greeting(message: string): void;
}
interfaceを継承
interface Nameable {
name: string;
}
interface Human extends Nameable {
age: number;
greeting(message: string): void;
}
const human: Human = {
name: 'masaki',
age: 28,
greeting(message: string) {
console.log(message);
},
};
?
あってもなくてもいい型interface Nameable {
name: string;
nickName?: string;
}
const hoge: Nameable = {
name: 'masaki',
};
関数の部分型
(obj: MyObj2)=>void型の値を(obj: MyObj)=>void型の値として扱うことができる 逆にするとエラーinterface MyObj {
foo: string;
bar: number;
}
interface MyObj2 {
foo: string;
}
const a: (obj: MyObj2) => void = () => {};
const b: (obj: MyObj) => void = a;
引数に関しても同じことができる
引数を 1 つだけ受け取る関数は、引数を 2 つ受け取る関数として使うことが可能であるということ
const f1: (foo: string) => void = () => {};
const f2: (foo: string, bar: number) => void = f1;