lonewarrior556
lonewarrior556

Reputation: 4479

How do you specify either one type or another

here's the general gist of what I am trying to do

type A = number | any[]  

declare const a: A

a.slice(1) // type error slice does not exist on Type A

link

How do I specify the return value of a function if indeed it can be either a number or an array?

I assumed that is how the | worked ie.

type A = number | string | any[]  

declare const a: A // a can be either a number, string or array

a.slice(0,1) // a is a string or array
.concat([1,2]) // a is an array

Upvotes: 2

Views: 2167

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

if a is array an in first example

type A = number | any[]  

const a: A = []; // add a value like this ts will infer that a is an array 
a.slice(1); 

or you can use casting

(a as any[]).slice(1);

With TypeScript 2.0, the type checker analyses all possible flows of control in statements and expressions to produce the most specific type possible (the narrowed type) at any given location for a local variable or parameter that is declared to have a union type.

type A = number | string | any[]  

declare const a: A ;  // assigning a value 

if (typeof a === 'string' ){
  console.log(a.toString());
}else if (typeof a === 'number') {
  console.log(a++);
} else if ( a instanceof Array) {
 a.slice(0,1).concat([1,2])
}

TypeScript 2.0: Control Flow Based Type Analysis

Upvotes: 3

Related Questions