Edo
Edo

Reputation: 1589

How can I enforce TypeScript to give an error on this code?

Usually in TypeScript i define pretty complex types so I never get this problem but I can't find an easy way to solve it.

type first = number;
type second = number;

let f: first = 1;
let s: second = 2;

const func = (arg1: first, arg2: second) => { };

func(s, f);

I expect to get an error from this code because I define the function with a first argument of type "first" and the second one of type "second" but when I call it I pass two arguments of inverted types

Upvotes: 1

Views: 147

Answers (2)

Aleksey L.
Aleksey L.

Reputation: 37918

Currently typescript doesn't support nominal typing. As a workaround people use type tagging/branding:

type First = number & { readonly _tag: unique symbol };
type Second = number & { readonly _tag: unique symbol };

let f = 1 as First;
let s = 2 as Second;

const func = (arg1: First, arg2: Second) => { };
func(s, f);  // Error: Types of property '_tag' are incompatible.

Upvotes: 2

Oscar Paz
Oscar Paz

Reputation: 18292

TypeScript doesn't care about type names (or aliases), just about the shape of the type. Both types first and second are the same type for the compiler, wo you won't get an error.

In fact, due to Structural Typing, this code will also work:

interface I1 {
  name: string;
  age: number;
}

interface I2 {
  age: number;
  name: string;
}

var a1: I1;
var a2: I2;

function log(arg1: I1, arg2: I2): void {
  console.log(arg1, arg2);
}

log(a2, a1);

because, I1 and I2 are also aliases to the same type (both interfaces have the same properties with the same types)

Upvotes: 0

Related Questions