ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.44k stars 31 forks source link

Possibility to make `as const` unnecessary #90

Closed fratzinger closed 1 year ago

fratzinger commented 1 year ago

Maybe there is a way to remove the necessity of as const. Please view the following example:

type Narrow<T> =
  | T extends Function ? T : never
  | T extends string | number | boolean | bigint ? T : never 
  | T extends [] ? [] : never 
  | { [K in keyof T]: Narrow<T[K]> }

declare function test<T>(a: Narrow<T>): T

const asConst = test(['string', 'literal', 123])
// of type ['string', 'literal', 123]

Play with it in TS Playground

Source: https://twitter.com/hd_nvim/status/1578567206190780417

ThomasAribart commented 1 year ago

Hi @fratzinger and thanks for the issue !

I like the idea of staying only at type level and not impacting compiled code, which would happen using such a function. Also, this will not be compatible with actual .json schemas once import schema from './schema.json' as const is implemented in TS.

However, I do not see any harm in exposing such a function for those who want to use it (FromSchema is already compatible with non-readonly schema types), so yes, I'll implement and document it !

ThomasAribart commented 1 year ago

@fratzinger Should be available in 2.6.0 !

There is an issue with my JS exports though, which use import/export syntax that is not compatible with cjs. The issue has been raised in https://github.com/ThomasAribart/json-schema-to-ts/issues/97 so we can close this one if it's good for you !

fratzinger commented 1 year ago

Nice. Thanks for your work and this great package! 🙏