(TypeScript) Regarding Reference Type Values, Their Types Should Be Included in the Types of the Places Where They Will Be Assigned

·

3 min read

Let me introduce this by dividing 'Array' and 'Normal Object'.

Array

Function Parameter

type OneToThree = (1 | 2 | 3)[];
type OneToFive = (1 | 2 | 3 | 4 | 5)[];

const target: OneToFive = [1, 2, 3];

function fn(arr: OneToThree) {}

fn(target); // error

That makes an error. That is because the type of the argument, which is type OneToFive, is larger than the type of the parameter, which is type OneToThree. Even though 'target' is included in the type of OneToThree, it happens.

It can be confusing when a type of an argument is not designated because the type is inferred as 'general' type.

type OneToThree = (1 | 2 | 3)[];

const target = [1, 2, 3];

function fn(arr: OneToThree) {}

fn(target); // error

If you hover on 'target', the message says this.

Argument of type 'number[]' is not assignable to parameter of type 'OneToThree'.

Function Return Value

Not only function parameters, function return values also follow the rule.

type OneToThree = (1 | 2 | 3)[];

function fn(): OneToThree {
  const target = [1, 2, 3];
  return target; // error
}

fn();

If you hover on 'return target', the message says this.

Type 'number[]' is not assignable to type 'OneToThree'.

Assigning Variables

The rule also applies to when assigning variables.

type OneToThree = (1 | 2 | 3)[];

const target = [1, 2, 3];

let target2: OneToThree;

target2 = target; // error

If you hover on 'target2', the message says this.

Type 'number[]' is not assignable to type 'OneToThree'.

Normal Object

Normal objects are same as arrays.

Function Parameter

interface NumObj {
  k1: 1 | 2;
  k2: 3 | 4;
}

const target = { k1: 1, k2: 3 };

function fn(numObj: NumObj) {}

fn(target); // error

If you hover on 'target', the message says this.

Argument of type '{ k1: number; k2: number; }' is not assignable to parameter of type 'NumObj'.

Function Return Value

interface NumObj {
  k1: 1 | 2;
  k2: 3 | 4;
}

function fn(): NumObj {
  const target = { k1: 1, k2: 3 };
  return target; // error
}

fn();

If you hover on 'return target', the message says this.

Type '{ k1: number; k2: number; }' is not assignable to type 'NumObj'.

Assigining Variables

interface NumObj {
  k1: 1 | 2;
  k2: 3 | 4;
}

const target = { k1: 1, k2: 3 };

let target2: NumObj;

target2 = target; // error

If you hover on 'target2', the message says this.

Type '{ k1: number; k2: number; }' is not assignable to type 'NumObj'.