Is it possible to use a union type as a key in an interface? For example, I want to do something like this:
interface IMargin { [key in 'foo' | 'bar']: boolean; }
But I'm getting this error:
A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1169)
Is there any way around this?
The use case is turning an array of values into an interface:
const possibleTypes = ['foo', 'bar']; interface Types { foo?: boolean; bar?: boolean; }
How to get the keys of a TypeScript interface? To get the union of the keys of a TypeScript interface, we can use the keyof keyword. interface Person { name: string; age: number; location: string; } type Keys = keyof Person; to create the Keys type by setting it to keyof Person .
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.
Union types are used when a value can be more than a single type. Such as when a property would be string or number .
TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type.
You can use an object type instead of an interface, which are mostly interchangeable:
type IMargin = { [key in 'foo' | 'bar']: boolean; }
This is not necessarily an answer, but I think this may interest others.
You can use a Union Type as a key in a sub-property of an Interface.
export type Language = 'EN' | 'DE' | 'IT'; export interface Document { generic: string; languages: { [key in Language]: string[]; } }
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