jecki / ts2python

Python-interoperability for Typescript-Interfaces
Apache License 2.0
39 stars 3 forks source link

Affect output with directives #17

Open Tatsh opened 7 months ago

Tatsh commented 7 months ago

I am thinking it would be nice to specify a few behaviour changes with directives. I propose the @ symbol inline with // @ts-expect-error, etc.

Imports required

// @ts2py-from uuid import UUID
// @ts2py-import requests

type UUIDOrRequestString = UUID | requests.Request | string;

(Currently requests.Requests will output requestsRequests.)

The above would add from uuid import UUID and import requests to the preamble. It might be nice to allow inline comments of this kind too: type x = Y; // @from z import Y. There should be no quotes or use of

Ability to skip helper types

This is mainly to keep the TypeScript references working so the type definitions are not just for ts2python. It can also be used for just ignoring a type if it is not needed in the Python output.

type integer = number; // @ts2py-discard
interface ConnectionParameters {
  network_timeout: integer;
}

The above integer type would not be output in the Python file.

Force use of TypeAlias hint

Some types are output fully as strings, which may not be recognised by an editor.

type JSONPrimitives = null | boolean | number | integer | string;
type JSONSerializableMapping = Mapping<
  string,
  JSONPrimitives | JSONSerializableMapping | (JSONPrimitives | JSONSerializableMapping)[]
>; // @ts2py-TypeAlias

The above would output:

from typing import TypeAlias
JSONPrimitives = None | bool | float | int | str
JSONSerializableMapping: TypeAlias = 'Mapping[str, JSONPrimitives | JSONSerializableMapping | list[JSONPrimitives | JSONSerializableMapping]]'

whereas currently no hint is output.