🧂
【型・クラスをさらっと】TypeScriptのextendsを知ろう
概要
別記事を書くにあたりextendsを理解しようの会
extendsとは
諸々を拡張するために使用するもの。主に
- 型の設定時
- クラスの継承
で使用される。
型の設定時
参考: https://typescriptbook.jp/reference/generics/type-parameter-constraint 、 https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
型定義をする際、ちょっとした縛りを設けて定義したい時や元々定義した型から拡張して新しい型を定義する時に使う。
ジェネリクス型を用いた使用例
function formatWithConstraint<T>(params: T): { key: T } {
return { key: params };
}
// ↑でも問題ないが↓にすることで引数paramをstringかnumberのみ許容にしている
function formatWithConstraint<T extends string | number>(params: T): { key: T } {
return { key: params };
}
// 関数の使用例
formatWithConstraint("1"); // ✅OK
formatWithConstraint(1); // ✅OK
formatWithConstraint([1]); // 🚫エラーになる
interfaceに対しての使用例
interface Value {
value: string;
}
// ↓にすることでvalue:stringを再定義せずValueから拡張した型KeyValueを定義できる
interface KeyValue extends Value {
key: string;
}
// 使用例
const hoge: KeyValue = { value: "hogeValue", key: "hogeKey" }; // ✅OK
const hoge: KeyValue = { key: "hogeKey" }; // 🚫エラーになる
Conditional Typesでの使用例
interface Value {
value: string;
}
interface KeyValue {
key: string;
value: string
}
// 型定義をする際の条件(Conditional Types)の条件文で使用、↓の場合はstringになる
type Hoge = KeyValue extends Value ? string : number; // string
// 使用例
const hoge: Hoge = "1"; // ✅OK
const hoge: Hoge = 1; // 🚫エラーになる
ジェネリクス型やConditional Typesの説明は別記事にて記載ずみ。
クラスの継承
参考: https://www.typescriptlang.org/docs/handbook/2/classes.html#extends-clauses
1つのクラスを定義した後、そのクラスを用いて別のクラスを定義したい時に使う。
class Animal {
move() {
console.log("動くよ");
}
}
class Dog extends Animal {
woof(times: number) {
for (let i = 0; i < times; i++) {
console.log("わおーん");
}
}
}
のように Aminal
をextendsしたクラス Dog
を定義したら以下のようにmove()にもwoof()にもアクセスできるようになっている。
const pochi = new Dog();
pochi.move();
pochi.woof(3);
Discussion