31

Looks like in TypeScript it's absolutely fine (from the compiler perspective) to have such code:

class Vehicle {
    public run(): void { console.log('Vehicle.run'); }
}

class Task {
    public run(): void { console.log('Task.run'); }
}

function runTask(t: Task) {
    t.run();
}

runTask(new Task());
runTask(new Vehicle());

But at the same time I would expect a compilation error, because Vehicle and Task don't have anything in common.

And sane usages can be implemented via explicit interface definition:

interface Runnable {
    run(): void;
}

class Vehicle implements Runnable {
    public run(): void { console.log('Vehicle.run'); }
}

class Task implements Runnable {
    public run(): void { console.log('Task.run'); }
}

function runRunnable(r: Runnable) {
    r.run();
}

runRunnable(new Task());
runRunnable(new Vehicle());

... or a common parent object:

class Entity {
    abstract run(): void;
}

class Vehicle extends Entity {
    public run(): void { console.log('Vehicle.run'); }
}

class Task extends Entity {
    public run(): void { console.log('Task.run'); }
}

function runEntity(e: Entity) {
    e.run();
}

runEntity(new Task());
runEntity(new Vehicle());

And yes, for JavaScript it's absolutely fine to have such behaviour, because there is no classes and no compiler at all (only syntactic sugar) and duck typing is natural for the language. But TypeScript tries to introduce static checks, classes, interfaces, etc. However duck typing for class instances looks rather confusing and error-prone, in my opinion.

3
  • 1
    Because Anders allows it. I don't know if he'll wander by and let you know why, tho. Commented Feb 16, 2018 at 15:21
  • @MuratK. nope, if you change the return type to number it still compiles. Commented Feb 16, 2018 at 15:23
  • Yeah I checked it. It works if return types are the same apparently Commented Feb 16, 2018 at 15:23

2 Answers 2

30

This is the way structural typing works. Typescript has a structural type system to best emulate how Javscript works. Since Javascript uses duck typing, any object that defines the contract can be used in any function. Typescript just tries to validate duck typing at compile time instead of at runtime.

Your problem will however only manifest for trivial classes, as soon as you add privates, classes become incompatible even if they have the same structure:

class Vehicle {
    private x: string;
    public run(): void { console.log('Vehicle.run'); }
}

class Task {
    private x: string;
    public run(): void { console.log('Task.run'); }
}

function runTask(t: Task) {
    t.run();
}

runTask(new Task());
runTask(new Vehicle()); // Will be a compile time error

This behavior also allows you to not explicitly implement interfaces, for example you function could define the interface for the parameter inline, and any class that satisfies the contract will be compatible even if they don't explicitly implement any interface:

function runTask(t: {  run(): void }) {
    t.run();
}

runTask(new Task());
runTask(new Vehicle());

On a personal note, coming from C# this was seemed insane at first, but when it comes to extensibility this way of type checking allows for much greater flexibility, once you get used to it you will see the benefits.

Sign up to request clarification or add additional context in comments.

12 Comments

@ivan i think that typescript would benefit from "unduckable types" ... tell me when you open a proposal, i will support that :)
@JonasW. I'm pretty sure there is one, in the mean time, the simple solution is to add a private, you don't even have to use it, so there is no runtime penalty, class Task { private unduckable : true } is enough, at runtime unduckable will not exist
@titian i know but that is a bad workaround. I use e.g. type userID = string , type groupID = string to distuinguish both as they are quite similar. And it would be nice to prevent the duck typing there.
@JonasW. The typescript compiler team does something similar, and that is where I got the idea to add the properties to make types incompatible. From the TS compiler code : export type Path = string & { __pathBrand: any }; github.com/Microsoft/TypeScript/blob/master/src/compiler/…
Just for sake of clarity: Structural typing and Duck typing are more or less the same thing, and the contrasting type system of these two is called Nominal typing: en.wikipedia.org/wiki/Nominal_type_system
|
6

It is now possible to create nominal types with TypeScript that allow you to discriminate types by context. Please consider the following question:

Atomic type discrimination (nominal atomic types) in TypeScript

With it's example:

export type Kilos<T> = T & { readonly discriminator: unique symbol };
export type Pounds<T> = T & { readonly discriminator: unique symbol };

export interface MetricWeight {
    value: Kilos<number>
}

export interface ImperialWeight {
    value: Pounds<number>
}

const wm: MetricWeight = { value: 0 as Kilos<number> }
const wi: ImperialWeight = { value: 0 as Pounds<number> }

wm.value = wi.value;                  // Gives compiler error
wi.value = wi.value * 2;              // Gives compiler error
wm.value = wi.value * 2;              // Gives compiler error
const we: MetricWeight = { value: 0 } // Gives compiler error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.