Exercices CM 1

This commit is contained in:
khannurien
2026-01-16 20:21:02 +01:00
parent ed3100a3e7
commit 1eb0ffc866
7 changed files with 230 additions and 0 deletions

52
exercice3.ts Normal file
View File

@@ -0,0 +1,52 @@
interface Animal {
name: string;
}
interface Dog extends Animal {
bark: () => void;
}
interface Cat extends Animal {
meow: () => void;
}
const makeNoise = (animal: Animal) => {
if (animal instanceof Dog) {
// 'Dog' fait uniquement référence à un type mais s'utilise en tant que valeur ici.ts(2693)
animal.bark();
}
};
namespace TaggedUnion {
interface Dog {
kind: "dog"; // Tagged union
bark: () => void;
}
interface Cat {
kind: "cat"; // Tagged union
meow: () => void;
}
type Animal = Dog | Cat;
const makeNoise = (animal: Animal) => {
if (animal.kind === "dog") animal.bark();
else animal.meow();
};
const dog: Dog = {
kind: "dog",
bark: () => console.log("bark"),
};
makeNoise(dog);
}
namespace Classes {
class Dog {
constructor(public name: string, public bark: () => void) {}
}
class Cat {
constructor(public name: string, public meow: () => void) {}
}
type Animal = Dog | Cat;
const makeNoise = (animal: Animal) => {
if (animal instanceof Dog) animal.bark();
else animal.meow();
};
const dog = new Dog("Fido", () => console.log("bark"));
makeNoise(dog);
}