3 ms·
> which are true nominal typing. One part that was not clear to me without testing, and since I do not use typescript regularly, was that you only get nominal
by davorak 2y ago
> which are true nominal typing.
One part that was not clear to me without testing, and since I do not use typescript regularly, was that you only get nominal typing between the classes that share the private member and if you start going out side that set you lose nominal typing. So you do not get a nominal type, but you can get a subset of types that when interacting with each other act as if they were nominal types.
So class Cat that uses `private __force_nominal!: void` can still be used as class Dog if Dog does not have `private __force_nominal!: void`.
Example[1]:
class Dog {
breed: string
constructor(breed: string) {
this.breed = breed
}
}
function printDog(dog: Dog) {
console.log("Dog: " + dog.breed)
}
class Cat {
private __force_nominal!: string
breed: string
constructor(breed: string) {
this.breed = breed
}
}
const shasta = new Cat("Maine Coon")
printDog(shasta)
edit - the above type checks in typescript 5.4.5
[1] modified example from https://asana.com/inside-asana/typescript-quirks https://asana.com/inside-asana/typescript-quirks
- ackfoobar 2y agoWithout your example, I would've bet that TS uses structural typing for interfaces and nominal typing for classes.
- DanielHB 2y agoI thought so too originally, was very surprised.
- davorak 2y agoThis is pretty much to flowjs does flowtype documentaiton: https://flow.org/en/docs/lang/nominal-structural/#toc-objects-are-structurally-typed https://flow.org/en/docs/lang/nominal-structural/#toc-object... Example: https://flow.org/try/#1N4Igxg9gdgZglgcxALlAIwIZoKYBsD6uEEAztvhgE6UYCe+JADpdhgCYowa5kA0I2KAFcAtiRQAXSkOz9sADwxgJ+NPTbYuQ3BMnTZA+Y2yU4IwRO4A6SFBIrGVDGM7c+h46fNRLuKxJIGWh8MeT0ZfhYlCStpHzNsFBAMIQkIEQwJODAQfiEyfBE4eWw2fDgofDBMsAALfAA3KjgsXGxxZC4eAw0G-GhcWn9aY3wWZldu-g1mbGqJUoBaCRHEzrcDEgBrbAk62kXhXFxJ923d-cPRHEpTgyEoMDaqZdW7vKgoOfaSKgOKpqmDA+d4gB5fMA-P6LCCMLLQbiLOoYCqgh6-GDYRYIXYLSgkRZkCR4jpddwPfJLZjpOBkO4AX34kA0SQA9KyAAQwIgAdxWxgAOj5VhyAPJoABWABURQBeDnADnUzwrZAc+ymKAIDn0gDcQv52DFkplxgATBz5YrlSZVeqpBVtXqhW0JByIJK1eLpasLVabZQ7QKQE1cDJgzr9VBXRyFvYvSa5e7JbqOeyOQB1CCULYkIVCp4YEgkDkAEQg2uAQo5NY5aBYpTVGsd1drtg1QmU2YAFPXsI37ZqEABKBWt2u1iS1WlWPulS11htscc6oX0-OwB7KODQJWaiTlhDdtgVtWH0dVqAT9sQNpWIhH4OHtURgDUHJPCFnS+Ha43heLDkAGFMjHK9aznNgmwdLUV3bKROzSSheyXaChwvFcJynGdIIXSCV3XKBCILaB7HVWoi0sBcvh5YDMm7YMAFkUS+YDiCgYNfygZgKgPCtuxICj7AwUd0wAUWobMAEJchDEwSB3KAkgaAAGKwzQAZgANisFSQHpIA https://flow.org/try/#1N4Igxg9gdgZglgcxALlAIwIZoKYBsD6uEEAzt...