Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union type as key in interface?

Tags:

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; } 
like image 564
Elliot Bonneville Avatar asked Mar 06 '19 12:03

Elliot Bonneville


People also ask

Can you get keys from an interface in TypeScript?

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 .

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.

When would one use a union type in TypeScript?

Union types are used when a value can be more than a single type. Such as when a property would be string or number .

How do you declare a union type variable in TypeScript?

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.


2 Answers

You can use an object type instead of an interface, which are mostly interchangeable:

type IMargin = {     [key in 'foo' | 'bar']: boolean; } 
like image 159
Dmitriy Avatar answered Sep 20 '22 13:09

Dmitriy


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[];   } } 
like image 32
Pablo Oliva Avatar answered Sep 21 '22 13:09

Pablo Oliva