Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python equivalent to TypeScript type unions?

In TypeScript you can create a type defined by a set of particular elements:

type Context = '2d' | 'webgl' | 'webgl2'

class CanvasFacade {
  constructor(ctx: Context) {}
}

Are there any recommended ways to achieve this in Python? Presumably using libraries such as typing? Enums?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re looking for typing.Union, for general unions. However, in Python, literal string types are not written as strings, so the type called '2d' in Typescript is equivalent to Literal['2d'] in Python, where Literal is also from typing.

Union[Literal['2d'], Literal['webgl'], Literal['webgl2']]

Now, if you’re using Python 3.10 or newer, you can benefit from PEP 604, which allows writing union types with the bitwise-or operator.

Literal['2d'] | Literal['webgl'] | Literal['webgl2']

Finally, because this "union of literals" pattern is so common, the Literal type supports it directly.

Literal['2d', 'webgl', 'webgl2']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading