Skip to content

Instantly share code, notes, and snippets.

@olivier-spinelli
Created September 29, 2023 08:21
Show Gist options
  • Save olivier-spinelli/029251012c7ca671cc0bd841af60bfd4 to your computer and use it in GitHub Desktop.
Save olivier-spinelli/029251012c7ca671cc0bd841af60bfd4 to your computer and use it in GitHub Desktop.
TypeScript nominal typing for class
/*
// 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