Transcrypt icon indicating copy to clipboard operation
Transcrypt copied to clipboard

Problem with typing.Union and typing.NewType

Open wrpscott opened this issue 8 years ago • 2 comments

When using type aliases in transcrypt 3.6.49, js code is produced for the statements. These then fail at runtime. For example, the following will compile with the '-dc -ds -n ' flags, but at runtime, will fail in the browser with 'TypeError: typing.Union is undefined[Learn More]'

import typing

SimpleStringType = str

QueryType = typing.NewType('QueryType', str)

CombiType = typing.Union[str, dict]

ConnectionOptions = typing.Dict[str, str]
Address = typing.Tuple[str, int]
Server = typing.Tuple[Address, ConnectionOptions]

def func_one(q: QueryType, c: CombiType) -> None:
    pass

wrpscott avatar Sep 12 '17 23:09 wrpscott

Thanks for the report! Type aliases are not yet supported. I will take a look in what it takes to start supporting them.

Kind regards Jacques

JdeH avatar Sep 13 '17 06:09 JdeH

I would like to +1 this FR! The Transcrypt documentation says:

Static typing support comes completely integrated in the Transcrypt distribution. All you have to do is add type annotations in your code at strategic places, e.g. API's and compile with the -ds / --dstat command line switch.

But, there are a few cases where this isn't true. For example, I have some complex types like this:

StringProducer = Callable[['Entity'], str]
StringSetProducer = Callable[['Entity'], set[str]]
DynamicString = Union[str, StringProducer]

# A DynamicStringSet can either be a set of strings, a function that produces a
# set of strings, or a set of DynamicStrings | StringSetProducers.
# StringSetProducers inside the set will get flattened into the resulting set.
DynamicStringSet = Union[Collection[Union[DynamicString, StringSetProducer]],
                         StringSetProducer]

Even though this type information isn't really used at runtime, you still have to __pragma__("skip") these and provide dummies so that other modules that import these type aliases don't fail:

# __pragma__("ecom")
'''?
StringProducer = object
StringSetProducer = object
DynamicString = object
DynamicStringSet = object
?'''
# __pragma__("noecom")

This is a bit cumbersome for any project which has really embraced type annotations...

iffyb avatar Aug 12 '21 00:08 iffyb