Created
September 29, 2023 08:21
-
-
Save olivier-spinelli/029251012c7ca671cc0bd841af60bfd4 to your computer and use it in GitHub Desktop.
TypeScript nominal typing for class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
// We need an index to generate the "brand" field. | |
// This correctly handles the inheritance. | |
class Duck { | |
private _0: undefined; | |
constructor(public name: string) { | |
} | |
} | |
class Dog extends Duck { | |
private _1: undefined; | |
constructor(name: string) { super(name);} | |
} | |
function play(duck: Duck, dog: Dog) { | |
console.log(`Play with ${duck.name} and ${dog.name}`) | |
} | |
const duck = new Duck('Jess') | |
const dog = new Dog('Loki') | |
play(duck, dog) // okay | |
// A 'Dog' is a 'Duck'. | |
// But a 'Duck' is not a 'Dog': this doesn't compile because of the second duck parameter. | |
play(dog, duck) // error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment