Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple type signatures for members, Union Types in TypeScript

Tags:

typescript

If I have a property that might be a string or a boolean how do I define it:

interface Foo{     bar:string;     bar:boolean; } 

I don't want to resort to:

interface Foo{     bar:any; } 

I don't think its possible without any. You can answer any of these:

Have I overlooked a spec and its possible right now? Is something like this planned? Has a feature request been logged?

I would imagine something like this:

interface Foo{     bar:string;     bar:boolean;     bar:any;  }  var x:Foo = <any>{}; x.bar="asdf"; x.bar.toUpperCase(); // intellisence only for string  
like image 445
basarat Avatar asked Aug 01 '13 22:08

basarat


People also ask

How do you declare a variable with multiple types in TypeScript?

Use a union type to define an array with multiple types in TypeScript, e.g. const arr: (string | number)[] = ['a', 1] . A union type is formed from two or more other types. The array in the example can only contain values of type string and number .

Can a variable have multiple types TypeScript?

In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc). A union type allows us to define a variable with multiple types.

How do I assign two TypeScript types?

TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.

How do you handle a union type in TypeScript?

TypeScript Union Type Narrowing To narrow a variable to a specific type, implement a type guard. Use the typeof operator with the variable name and compare it with the type you expect for the variable.


2 Answers

As of 2015, union-types work:

interface Foo {     bar:string|boolean; } 
like image 98
MarcG Avatar answered Sep 20 '22 09:09

MarcG


This is usually referred to as "union types". The TypeScript type system from 1.4 does allow for this.

See: Advanced Types

like image 41
Ryan Cavanaugh Avatar answered Sep 19 '22 09:09

Ryan Cavanaugh