Multiple type signatures for members, Union Types in TypeScript

Typescript

Typescript Problem Overview


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 

Typescript Solutions


Solution 1 - Typescript

As of 2015, union-types work:

interface Foo {
    bar:string|boolean;
}

Solution 2 - Typescript

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

See: Advanced Types

Solution 3 - Typescript

Not saying this answers your question, but could you resort to something like this?

interface Foo<T>{
	bar:T;
}

function createFoo<T>(bar:T) : Foo<T>{
	return {bar:bar};
}

var sFoo = createFoo("s");
var len = sFoo.bar.length;

var bFoo = createFoo(true);
var result = bFoo.bar === true;

Solution 4 - Typescript

something like that?

interface Base<T, T2> {
  a: T;
  b: T2;
}

type FirstExtendedBase = Base<boolean, string>;

const exampleOne: FirstExtendedBase = {
  a: false,
  b: '',
};

type SecondExtendedBase = Base<number, Date>;

const exampleTwo: SecondExtendedBase = {
  a: 42,
  b: new Date(),
};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbasaratView Question on Stackoverflow
Solution 1 - TypescriptMarcGView Answer on Stackoverflow
Solution 2 - TypescriptRyan CavanaughView Answer on Stackoverflow
Solution 3 - TypescriptDamianView Answer on Stackoverflow
Solution 4 - TypescriptValentin BossiView Answer on Stackoverflow