fix(types): JSONParsed infer unknown values (#4405)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jonathan Haines · committed by GitHub · parent 5ece995 · Browse files · 4 files·+140 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+140 added−27 removed
- tests:+106 added−6 removed
- other:+34 added−21 removed
Provenance
- Commit
f8c9b6e- Tree
818d34c- Author
Jonathan Haines <jonno.haines@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
5ece995
4 files changed+140 added−27 removed
modified:src/client/client.test.ts+38 added
10 unmodified lines11 import { validator } from '../validator'12 import { hc } from './client'13 import type { ClientResponse, InferRequestType, InferResponseType } from './types'14 15+class SafeBigInt {16+ unsafe = BigInt(42)17+18+ toJSON() {19+ return {20+ value: '42n',21+ }22+ }23+}24+25 describe('Basic - JSON', () => {26 const app = new Hono()27 28 const route = app31 unmodified lines60 )61 .get('/hello-not-found', (c) => c.notFound())62 .get('/null', (c) => c.json(null))63 .get('/empty', (c) => c.json({}))64+ .get('/bigint', (c) => c.json({ value: BigInt(42) }))65+ .get('/safe-bigint', (c) => c.json(new SafeBigInt()))66 67 type AppType = typeof route68 69 const server = setupServer(22 unmodified lines92 }),93 http.get('http://localhost/empty', () => {94 return HttpResponse.json({})95 }),96+ http.get('http://localhost/bigint', () => {97+ return HttpResponse.json({ value: BigInt(42) })98+ }),99+ http.get('http://localhost/safe-bigint', () => {100+ return HttpResponse.json(new SafeBigInt())101+ }),102 http.get('http://localhost/api/string', () => {103 return HttpResponse.json('a-string')104 }),105 http.get('http://localhost/api/number', async () => {62 unmodified lines168 expectTypeOf(data).toMatchTypeOf<{}>()169 expect(data).toStrictEqual({})170 })171 172+ it('Should get a `{}` content', async () => {173+ const client = hc<AppType>('http://localhost')174+ const res = await client['safe-bigint'].$get()175+ const data = await res.json()176+ expectTypeOf(data).toMatchTypeOf<{ value: string }>()177+ expect(data).toStrictEqual({ value: '42n' })178+ })179+180+ it('Should get an error response', async () => {181+ const client = hc<AppType>('http://localhost')182+ const res = await client.bigint.$get()183+ const data = await res.json()184+ expectTypeOf(data).toMatchTypeOf<never>()185+ expect(res.status).toBe(500)186+ expect(data).toMatchObject({187+ message: 'Do not know how to serialize a BigInt',188+ name: 'TypeError',189+ })190+ })191+192 it('Should have correct types - primitives', async () => {193 const app = new Hono()194 const route = app195 .get('/api/string', (c) => c.json('a-string'))1224 unmodified linesmodified:src/utils/types.test.ts+68 added-6 removed
1-import type { Equal, Expect, JSONParsed } from './types'1+import type { JSONParsed, JSONValue } from './types'2 3 describe('JSONParsed', () => {4 enum SampleEnum {5 Value1 = 'value1',71 unmodified lines77 type Actual = JSONParsed<() => void>78 type Expected = never79 expectTypeOf<Actual>().toEqualTypeOf<Expected>()80 })81+ it('should convert bigint type to never', () => {82+ type Actual = JSONParsed<bigint>83+ type Expected = never84+ expectTypeOf<Actual>().toEqualTypeOf<Expected>()85+ })86 })87 88 describe('array', () => {89 it('should convert undefined[] type to null[]', () => {68 unmodified lines158 expectTypeOf<Actual>().toEqualTypeOf<Expected>()159 })160 })161 162+ describe('unknown', () => {163+ it('should convert unknown type to unknown', () => {164+ type Actual = JSONParsed<unknown>165+ type Expected = JSONValue166+ expectTypeOf<Actual>().toEqualTypeOf<Expected>()167+ })168+169+ it('Should convert unknown value to JSONValue', () => {170+ type Actual = JSONParsed<{ value: unknown }>171+ type Expected = { value: JSONValue }172+ expectTypeOf<Actual>().toEqualTypeOf<Expected>()173+ })174+ })175+176 describe('Set/Map', () => {177 it('should convert Set to empty object', () => {178 type Actual = JSONParsed<Set<number>>179 type Expected = {}37 unmodified lines217 type Expected = {218 datetime: string219 }220 type Actual = JSONParsed<Post>202- // eslint-disable-next-line @typescript-eslint/no-unused-vars203- type verify = Expect<Equal<Expected, Actual>>221+ expectTypeOf<Actual>().toEqualTypeOf<Expected>()222 })223 224 it('Should convert bigint to never', () => {225 type Post = {226 num: bigint227 }228+ type Expected = never229+ type Actual = JSONParsed<Post>230+ expectTypeOf<Actual>().toEqualTypeOf<Expected>()231+ })232+233+ it('Should convert bigint when TError is provided', () => {234+ type Post = {235+ num: bigint236+ }237 type Expected = {211- num: never238+ num: JSONValue239 }240+ type Actual = JSONParsed<Post, never>241+ expectTypeOf<Actual>().toEqualTypeOf<Expected>()242+ })243+244+ it('Should convert bigint[] to never', () => {245+ type Post = {246+ nums: bigint[]247+ }248+ type Expected = never249 type Actual = JSONParsed<Post>214- // eslint-disable-next-line @typescript-eslint/no-unused-vars215- type verify = Expect<Equal<Expected, Actual>>250+ expectTypeOf<Actual>().toEqualTypeOf<Expected>()251 })252+253+ it('Should convert bigint[] when TError is provided', () => {254+ type Post = {255+ num: bigint[]256+ }257+ type Expected = {258+ num: JSONValue[]259+ }260+ type Actual = JSONParsed<Post, never>261+ expectTypeOf<Actual>().toEqualTypeOf<Expected>()262+ })263+264+ it('Should parse bigint with a toJSON function', () => {265+ class SafeBigInt {266+ unsafe = BigInt('42')267+268+ toJSON() {269+ return {270+ unsafe: '42n',271+ }272+ }273+ }274+275+ type Actual = JSONParsed<SafeBigInt>276+ type Expected = { unsafe: string }277+ expectTypeOf<Actual>().toEqualTypeOf<Expected>()278+ })279 })modified:src/utils/types.ts+32 added-10 removed
39 unmodified lines4041424344454445464748495051525354555657585960616263646550666768697071565772737475767760616263647879808182838485868788899031 unmodified lines39 unmodified lines */type OmitSymbolKeys<T> = { [K in keyof T as K extends symbol ? never : K]: T[K] }
export type JSONValue = JSONObject | JSONArray | JSONPrimitive// Non-JSON values such as `Date` implement `.toJSON()`, so they can be transformed to a value assignable to `JSONObject`:export type JSONParsed<T> = T extends { toJSON(): infer J }/** * Convert a type to a JSON-compatible type. * * Non-JSON values such as `Date` implement `.toJSON()`, * so they can be transformed to a value assignable to `JSONObject` * * `JSON.stringify()` throws a `TypeError` when it encounters a `bigint` value, * unless a custom `replacer` function or `.toJSON()` method is provided. * * This behaviour can be controlled by the `TError` generic type parameter, * which defaults to `bigint | ReadonlyArray<bigint>`. * You can set it to `never` to disable this check. */export type JSONParsed<T, TError = bigint | ReadonlyArray<bigint>> = T extends TError ? never : T extends { toJSON(): infer J } ? (() => J) extends () => JSONPrimitive ? J : (() => J) extends () => { toJSON(): unknown } ? {} : JSONParsed<J> : JSONParsed<J, TError> : T extends JSONPrimitive ? T : T extends InvalidJSONValue ? never : T extends ReadonlyArray<unknown> ? { [K in keyof T]: JSONParsed<InvalidToNull<T[K]>> } : T extends Set<unknown> | Map<unknown, unknown> ? { [K in keyof T]: JSONParsed<InvalidToNull<T[K]>, TError> } : T extends Set<unknown> | Map<unknown, unknown> | Record<string, never> ? {} : T extends object ? T[keyof T] extends TError ? never ? { [K in keyof OmitSymbolKeys<T> as IsInvalid<T[K]> extends true ? never : K]: boolean extends IsInvalid<T[K]> ? JSONParsed<T[K]> | undefined : JSONParsed<T[K]> } : { [K in keyof OmitSymbolKeys<T> as IsInvalid<T[K]> extends true ? never : K]: boolean extends IsInvalid<T[K]> ? JSONParsed<T[K], TError> | undefined : JSONParsed<T[K], TError> } : T extends unknown ? JSONValue : never
/** * Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.31 unmodified linesmodified:src/context.ts+2 added-11 removed
192 unmodified lines193 /**194 * @template T - The type of the JSON value or simplified unknown type.195 * @template U - The type of the status code.196 *197- * @returns {Response & TypedResponse<SimplifyDeepArray<T> extends JSONValue ? (JSONValue extends SimplifyDeepArray<T> ? never : JSONParsed<T>) : never, U, 'json'>} - The response after rendering the JSON object, typed with the provided object and status code types.197+ * @returns {Response & TypedResponse<JSONParsed<T>, U, 'json'>} - The response after rendering the JSON object, typed with the provided object and status code types.198 */199 type JSONRespondReturn<200 T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,201 U extends ContentfulStatusCode202-> = Response &203- TypedResponse<204- SimplifyDeepArray<T> extends JSONValue205- ? JSONValue extends SimplifyDeepArray<T>206- ? never207- : JSONParsed<T>208- : never,209- U,210- 'json'211- >202+> = Response & TypedResponse<JSONParsed<T>, U, 'json'>203 204 /**205 * Interface representing a function that responds with HTML content.206 *563 unmodified lines