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
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 .
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.
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.
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.
As of 2015, union-types work:
interface Foo { bar:string|boolean; }
This is usually referred to as "union types". The TypeScript type system from 1.4 does allow for this.
See: Advanced Types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With