typtyp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
typtyp/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from typtyp.world import World
2
+
3
+ __all__ = [
4
+ "World",
5
+ ]
typtyp/excs.py ADDED
@@ -0,0 +1,2 @@
1
+ class UnreferrableTypeError(ValueError):
2
+ pass
typtyp/py.typed ADDED
File without changes
typtyp/type_info.py ADDED
@@ -0,0 +1,11 @@
1
+ import dataclasses
2
+
3
+
4
+ @dataclasses.dataclass(frozen=True)
5
+ class TypeInfo:
6
+ name: str
7
+ type: type
8
+ doc: str | None = None
9
+
10
+ # Consider `null`s in e.g. dataclasses as `undefined` in TypeScript
11
+ null_is_undefined: bool = False
typtyp/typescript.py ADDED
@@ -0,0 +1,275 @@
1
+ from __future__ import annotations
2
+
3
+ import collections
4
+ import collections.abc
5
+ import dataclasses
6
+ import datetime
7
+ import decimal
8
+ import enum
9
+ import inspect
10
+ import ipaddress
11
+ import json
12
+ import pathlib
13
+ import re
14
+ import textwrap
15
+ import types
16
+ import typing
17
+ import uuid
18
+ from collections.abc import Iterable
19
+ from typing import TYPE_CHECKING, Any, ForwardRef, NamedTuple, TextIO, TypeVar
20
+
21
+ from typtyp.excs import UnreferrableTypeError
22
+ from typtyp.type_info import TypeInfo
23
+
24
+ if TYPE_CHECKING:
25
+ from typtyp.world import World
26
+
27
+
28
+ RECORD_KEY_TS_TYPE = "string | number | symbol"
29
+
30
+
31
+ def is_pydantic_model(t) -> bool:
32
+ try:
33
+ from pydantic import BaseModel
34
+
35
+ return issubclass(t, BaseModel)
36
+ except ImportError: # pragma: no cover
37
+ return False
38
+
39
+
40
+ class TypeAndKind(NamedTuple):
41
+ type: type
42
+ kind: str | None
43
+
44
+
45
+ @dataclasses.dataclass(frozen=True)
46
+ class TypeScriptContext:
47
+ fp: TextIO
48
+ world: World
49
+ null_is_undefined: bool = False
50
+ required_utility_types: dict[str, type] = dataclasses.field(default_factory=dict)
51
+
52
+ def sub(self, **replacements):
53
+ return dataclasses.replace(self, **replacements)
54
+
55
+ def write(self, s: str) -> None:
56
+ self.fp.write(s)
57
+
58
+
59
+ def map_plain_type_ref(field_type: type, ts_context: TypeScriptContext) -> str: # noqa: C901, PLR0911, PLR0912
60
+ try:
61
+ # This will handle enums as well – they need to have been registered
62
+ return ts_context.world.get_name_for_type(field_type)
63
+ except KeyError:
64
+ pass
65
+
66
+ # Special types
67
+
68
+ if isinstance(field_type, ForwardRef):
69
+ return f"unknown /* {field_type.__forward_arg__} */"
70
+ if type(field_type) is TypeVar:
71
+ return f"unknown /* {field_type} */"
72
+ if type(field_type) is type(Ellipsis):
73
+ return "unknown /* ... */"
74
+ if field_type is Any:
75
+ return "unknown /* any */"
76
+
77
+ if issubclass(field_type, (bytes, bytearray, memoryview)):
78
+ return f"unknown /* {field_type.__name__} */"
79
+
80
+ if issubclass(field_type, bool):
81
+ return "boolean"
82
+
83
+ if issubclass(field_type, complex):
84
+ return "[number, number] /* complex */"
85
+
86
+ if issubclass(field_type, (pathlib.Path, ipaddress._IPAddressBase, re.Pattern)):
87
+ return f"string /* {field_type.__name__} */"
88
+
89
+ if issubclass(field_type, (int, float, decimal.Decimal, datetime.timedelta)) and not issubclass(
90
+ field_type,
91
+ enum.Enum,
92
+ ):
93
+ return "number"
94
+
95
+ if issubclass(field_type, uuid.UUID):
96
+ ts_context.required_utility_types["UUID"] = str
97
+ return "UUID"
98
+
99
+ if issubclass(field_type, str) and not issubclass(field_type, enum.Enum):
100
+ return "string"
101
+
102
+ if issubclass(field_type, type(None)):
103
+ if ts_context.null_is_undefined:
104
+ return "undefined"
105
+ return "null"
106
+
107
+ if field_type is datetime.date:
108
+ ts_context.required_utility_types["ISO8601Date"] = str
109
+ return "ISO8601Date"
110
+
111
+ if field_type is datetime.time:
112
+ ts_context.required_utility_types["ISO8601Time"] = str
113
+ return "ISO8601Time"
114
+
115
+ if field_type is datetime.datetime:
116
+ ts_context.required_utility_types["ISO8601"] = str
117
+ return "ISO8601"
118
+
119
+ if issubclass(field_type, collections.Counter):
120
+ return f"Record<{RECORD_KEY_TS_TYPE}, number> /* Counter */"
121
+
122
+ if issubclass(field_type, dict):
123
+ comment = f" /* {field_type.__name__} */" if field_type is not dict else ""
124
+ return f"Record<{RECORD_KEY_TS_TYPE}, unknown>{comment}"
125
+
126
+ raise UnreferrableTypeError(f"Unable to refer to the type {field_type!r}; if it's a struct, add it to the world")
127
+
128
+
129
+ def to_ts_function_declaration(field_type: type, ts_context: TypeScriptContext) -> str:
130
+ tps = typing.get_args(field_type)
131
+ if len(tps) == 2:
132
+ args_list, retval = tps
133
+ arglist = ", ".join(f"_{i}: {to_ts_type(arg, ts_context)}" for i, arg in enumerate(args_list))
134
+ return f"({arglist}) => {to_ts_type(retval, ts_context)}"
135
+ if len(tps) == 0:
136
+ return "Function"
137
+ raise AssertionError(f"Expected Callable with 0 or 2 types, got {tps}")
138
+
139
+
140
+ def to_ts_type(field_type: type, ts_context: TypeScriptContext) -> str: # noqa: C901, PLR0911, PLR0912
141
+ if isinstance(field_type, typing.NewType):
142
+ tp = to_ts_type(field_type.__supertype__, ts_context) # pyright: ignore
143
+ return f"{tp} /* {field_type.__name__} */"
144
+
145
+ origin = typing.get_origin(field_type)
146
+
147
+ if origin is collections.abc.Callable:
148
+ return to_ts_function_declaration(field_type, ts_context)
149
+
150
+ if origin in (typing.Union, types.UnionType):
151
+ return " | ".join(to_ts_type(sub, ts_context) for sub in typing.get_args(field_type))
152
+
153
+ if origin is tuple:
154
+ tps = typing.get_args(field_type)
155
+ if tps and tps[-1] is Ellipsis:
156
+ if len(tps) != 2:
157
+ raise AssertionError(f"Expected tuple with one type and Ellipsis, got {tps}")
158
+ return f"[...{to_ts_type(tps[0], ts_context)}[]]"
159
+
160
+ return f"[{', '.join(to_ts_type(tp, ts_context) for tp in tps)}]"
161
+
162
+ if origin is typing.Literal:
163
+ return " | ".join(json.dumps(arg) for arg in typing.get_args(field_type))
164
+
165
+ # TODO: Smells like this could be done better with the ABCs...
166
+ if origin in (
167
+ list,
168
+ collections.deque,
169
+ set,
170
+ frozenset,
171
+ collections.abc.Iterable,
172
+ collections.abc.Iterator,
173
+ collections.abc.Sequence,
174
+ ):
175
+ comment = f" /* {origin.__name__} */" if origin is not list else ""
176
+ tps = typing.get_args(field_type)
177
+ if len(tps) != 1:
178
+ raise AssertionError(f"Expected list with one type, got {tps}")
179
+ inner = to_ts_type(tps[0], ts_context)
180
+ if inner.rstrip("[]").isalnum():
181
+ return f"({inner})[]{comment}"
182
+ return f"Array<{inner}>{comment}"
183
+
184
+ if origin is collections.Counter:
185
+ tps = typing.get_args(field_type)
186
+ if len(tps) != 1:
187
+ raise AssertionError(f"Expected Counter with one type, got {tps}")
188
+ return f"Record<{to_ts_type(tps[0], ts_context)}, number>"
189
+
190
+ if origin in (
191
+ dict,
192
+ collections.defaultdict,
193
+ collections.abc.Mapping,
194
+ collections.abc.MutableMapping,
195
+ collections.OrderedDict,
196
+ ):
197
+ comment = f" /* {origin.__name__} */" if origin is not dict else ""
198
+ tps = typing.get_args(field_type)
199
+ if len(tps) != 2:
200
+ raise AssertionError(f"Expected dict with two types, got {tps}")
201
+ return f"Record<{to_ts_type(tps[0], ts_context)}, {to_ts_type(tps[1], ts_context)}>{comment}"
202
+
203
+ if origin is not None:
204
+ raise NotImplementedError(f"Unknown origin {origin!r} for {field_type!r}") # pragma: no cover
205
+
206
+ if hasattr(field_type, "_fields") and issubclass(field_type, tuple):
207
+ # NamedTuple defined inline? I guess, why not...
208
+ fields: list[str] = field_type._fields # pyright: ignore
209
+ contents = (f"unknown /* {name} */" for name in fields)
210
+ return f"[{', '.join(contents)}] /* {field_type.__name__} */"
211
+
212
+ return map_plain_type_ref(field_type, ts_context)
213
+
214
+
215
+ def get_struct_types(tp) -> list[tuple[str, Any]] | None:
216
+ if dataclasses.is_dataclass(tp):
217
+ return [(f.name, f.type) for f in dataclasses.fields(tp)]
218
+
219
+ if typing.is_typeddict(tp):
220
+ # TODO: support __total__
221
+ # TODO: support __required_keys__
222
+ # TODO: support __optional_keys__
223
+ return list(inspect.get_annotations(tp).items())
224
+
225
+ try:
226
+ if is_pydantic_model(tp):
227
+ return [(name, f.annotation) for (name, f) in sorted(tp.model_fields.items(), key=lambda item: item[0])]
228
+ except TypeError: # pragma: no cover
229
+ pass
230
+
231
+ return None
232
+
233
+
234
+ def write_structlike(ctx: TypeScriptContext, type_info: TypeInfo, name_and_type: Iterable[tuple[str, type]]) -> None:
235
+ ctx = ctx.sub(null_is_undefined=type_info.null_is_undefined)
236
+ ctx.write(f"interface {type_info.name} {{\n")
237
+ for name, typ in name_and_type:
238
+ ts_type = to_ts_type(typ, ts_context=ctx).strip()
239
+ field_suffix = ""
240
+ if "| undefined" in ts_type:
241
+ ts_type = ts_type.replace("| undefined", "")
242
+ field_suffix = "?"
243
+ ctx.write(f"{name}{field_suffix}: {ts_type}\n")
244
+ ctx.write("}\n")
245
+
246
+
247
+ def write_enum(ctx: TypeScriptContext, type_info: TypeInfo) -> None:
248
+ ctx.write(f"const enum {type_info.name} {{\n")
249
+ for name, value in type_info.type.__members__.items(): # type: ignore
250
+ ctx.write(f"{name} = {json.dumps(value.value)},\n")
251
+ ctx.write("}\n")
252
+
253
+
254
+ def write_type(ctx: TypeScriptContext, type_info: TypeInfo) -> None:
255
+ if type_info.doc:
256
+ ctx.write("/**\n")
257
+ for line in textwrap.dedent(type_info.doc).strip().splitlines():
258
+ ctx.write(f" * {line}\n")
259
+ ctx.write(" */\n")
260
+
261
+ if isinstance(type_info.type, type) and issubclass(type_info.type, enum.Enum):
262
+ return write_enum(ctx, type_info)
263
+
264
+ if (nt := get_struct_types(type_info.type)) is not None:
265
+ write_structlike(ctx, type_info, nt)
266
+ else:
267
+ ctx.write(f"type {type_info.name} = {to_ts_type(type_info.type, ctx)}\n")
268
+
269
+
270
+ def write_ts(fp: typing.TextIO, world: World) -> None:
271
+ ctx = TypeScriptContext(fp=fp, world=world)
272
+ for type_info in ctx.world:
273
+ write_type(ctx, type_info)
274
+ for name, typ in sorted(ctx.required_utility_types.items()):
275
+ write_type(ctx, TypeInfo(name=name, type=typ))
typtyp/world.py ADDED
@@ -0,0 +1,73 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ from typing import Iterable
5
+
6
+ from typtyp.type_info import TypeInfo
7
+
8
+
9
+ class _Sentinel:
10
+ pass
11
+
12
+
13
+ NOT_SET = _Sentinel()
14
+
15
+
16
+ class World:
17
+ def __init__(self) -> None:
18
+ self._types_by_name: dict[str, TypeInfo] = {}
19
+ self._types_by_type: dict[type, TypeInfo] = {}
20
+
21
+ def add(
22
+ self,
23
+ /,
24
+ typ: type,
25
+ *,
26
+ name: str | None = None,
27
+ doc: str | None | _Sentinel = NOT_SET,
28
+ null_is_undefined: bool = False,
29
+ ) -> TypeInfo:
30
+ if name is None:
31
+ name = typ.__name__
32
+ if isinstance(doc, _Sentinel):
33
+ # You're not a real doc...
34
+ real_doc = getattr(typ, "__doc__", None)
35
+ else:
36
+ real_doc = doc
37
+ assert name # noqa: S101
38
+ if name in self._types_by_name:
39
+ raise KeyError(f"Type {name} already exists")
40
+ info = TypeInfo(name=name, type=typ, doc=real_doc, null_is_undefined=null_is_undefined)
41
+ self._types_by_name[name] = info
42
+ self._types_by_type[typ] = info
43
+ return info
44
+
45
+ def add_many(
46
+ self,
47
+ types: tuple[type, ...] | list[type] | set[type] | dict[str, type],
48
+ *,
49
+ doc: str | None | _Sentinel = NOT_SET,
50
+ null_is_undefined: bool = False,
51
+ ) -> dict[type, TypeInfo]:
52
+ types_it: Iterable[tuple[str | None, type]]
53
+ if isinstance(types, dict):
54
+ types_it = types.items()
55
+ else:
56
+ types_it = ((None, typ) for typ in types)
57
+ ret = {}
58
+ for name, typ in types_it:
59
+ ret[typ] = self.add(typ, name=name, doc=doc, null_is_undefined=null_is_undefined)
60
+ return ret
61
+
62
+ def get_name_for_type(self, t: type) -> str:
63
+ return self._types_by_type[t].name
64
+
65
+ def __iter__(self):
66
+ return iter(self._types_by_name.values())
67
+
68
+ def get_typescript(self) -> str:
69
+ from typtyp.typescript import write_ts
70
+
71
+ sio = io.StringIO()
72
+ write_ts(sio, self)
73
+ return sio.getvalue()
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: typtyp
3
+ Version: 0.1.0
4
+ Summary: Convert Python types to TypeScript
5
+ Author-email: Aarni Koskela <akx@iki.fi>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Provides-Extra: pydantic
10
+ Requires-Dist: pydantic>=2.0; extra == 'pydantic'
11
+ Description-Content-Type: text/markdown
12
+
13
+ # typtyp
14
+
15
+ Convert Python types and type annotations to TypeScript type definitions.
16
+
17
+ ## Features
18
+
19
+ - Convert dataclasses, TypedDict, enums, and Pydantic models to TypeScript
20
+ - Support for Python's standard typing primitives
21
+ - Rich type support (dates, UUIDs, complex collections, etc.)
22
+ - Simple API for declaring types for conversion
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pip install typtyp
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ```python
33
+ from dataclasses import dataclass
34
+ from typing import List, Optional
35
+ import typtyp
36
+
37
+ @dataclass
38
+ class User:
39
+ name: str
40
+ email: str
41
+ age: Optional[int] = None
42
+
43
+ @dataclass
44
+ class Team:
45
+ name: str
46
+ members: List[User]
47
+
48
+ # Create a world to collect types
49
+ world = typtyp.World()
50
+
51
+ # Add types to the world
52
+ world.add(User)
53
+ world.add(Team)
54
+
55
+ # Generate TypeScript
56
+ typescript_code = world.get_typescript()
57
+ print(typescript_code)
58
+ ```
59
+
60
+ Output (approximately – you would want to run typtyp's output through a formatter of your liking):
61
+
62
+ ```typescript
63
+ export interface User {
64
+ name: string;
65
+ email: string;
66
+ age: number | null;
67
+ }
68
+
69
+ export interface Team {
70
+ name: string;
71
+ members: User[];
72
+ }
73
+ ```
@@ -0,0 +1,10 @@
1
+ typtyp/__init__.py,sha256=CzgwvxUlYaSgj65zNMRqHsdEQh9ZFkaaYRMwowKDMs0,59
2
+ typtyp/excs.py,sha256=gcC6DwBKdBHQWnvMiqmK6abevP4g2fB5kIzp8Hxz0wo,50
3
+ typtyp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ typtyp/type_info.py,sha256=Lw1tFoT-qnhAveT2Q6HUwoHZX9jq2eoF_ZOLlvQK8OI,238
5
+ typtyp/typescript.py,sha256=CEqoxTI16adVmHC0JlAiaUzbOjL9Rc5XyGZwRPm_1CI,9391
6
+ typtyp/world.py,sha256=10C4W9HiYt7Cqgggzh1KR63eqkLyVt94kGnG4M1x0GE,2025
7
+ typtyp-0.1.0.dist-info/METADATA,sha256=D9UJ2e80q1PC7nOWixSqiKCqViOfNhmCGJ1WXp-msbQ,1422
8
+ typtyp-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ typtyp-0.1.0.dist-info/licenses/LICENSE,sha256=xSQKpXJYANUakzkPGkqcii_yPdONGXj-4QJIflE-Ehw,1094
10
+ typtyp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,22 @@
1
+
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2025 Aarni Koskela <akx@iki.fi>
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.