Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure that generic type only has primitive properties in Typescript

Tags:

typescript

I have a function that takes a generic type, and i need to ensure that that type is JSON-serializable (aka only primitive properties).

My attempt at this was to define an interface for what a JSON compatible type looks like, and enforce that my generic extends this type:

type JSONPrimitive = string | number | boolean | null
interface JSONObject {
  [prop: string]: JSONPrimitive | JSONPrimitive[] | JSONObject | JSONObject[]
}
export type JSONable = JSONObject | JSONPrimitive | JSONObject[] | JSONPrimitive[]

function myFunc<T extends JSONable>(thing: T): T {
  ...
}

// Elsewhere

// I know that if this was defined as a `type` rather than
// an `interface` this would all work, but i need a method
// that works with arbitrary types, including external interfaces which
// are out of my control
interface SomeType {
  id: string,
  name: string
}

myFunc<SomeType[]>(arrayOfSomeTypes)
// The above line doesn't work, i get: 
// Type 'SomeType[]' does not satisfy the constraint 'JSONable'.
//   Type 'SomeType[]' is not assignable to type 'JSONObject[]'.
//     Type 'SomeType' is not assignable to type 'JSONObject'.
//       Index signature is missing in type 'SomeType'.ts(2344)

The issue here seems to come down to the way index signatures work in typescript. Specifically, a type cannot extend a type with an index signature if it narrows the possible properties that the index signature allows. (ie SomeType doesn't allow you to arbitrarily add a foo property, but JSONable of course would. This issue is described further in this existing github issue.

So i know that the above doesn't really work, but the problem still persists that i need some reliable way to ensure that a generic type is JSON serializable. Any ideas?

Thanks in advance!

like image 689
Jemar Jones Avatar asked Dec 31 '22 16:12

Jemar Jones


1 Answers

The way I'd probably proceed here (in the absence of a fix or change to the underlying issue around implicit index signatures in interfaces) would be to represent your desired json type as something like a generic constraint like this:

type AsJson<T> = 
  T extends string | number | boolean | null ? T : 
  T extends Function ? never : 
  T extends object ? { [K in keyof T]: AsJson<T[K]> } : 
  never;

So AsJson<T> should be equal to T if T is a valid JSON type, otherwise it will have never in its definition somewhere. Then we can do this:

declare function myFunc<T>(thing: T & AsJson<T>): T;

which requires that thing be T (which infers T for you) intersected with AsJson<T>, which adds AsJson<T> as an additional constraint on thing. Let's see how it works:

myFunc(1); // okay
myFunc(""); // okay
myFunc(true); // okay
myFunc(null); // okay

myFunc(undefined); // error
myFunc(() => 1); // error
myFunc(console.log()); // error

myFunc({}); // okay
myFunc([]); // okay
myFunc([{a: [{b: ""}]}]); // okay

myFunc({ x: { z: 1, y: () => 1, w: "v" } }); // error!
//  --------------> ~
//  () => number is not assignable to never

And now your interface type is accepted:

interface SomeType {
  id: string;
  name: string;
}

const arrayOfSomeTypes: SomeType[] = [{ id: "A", name: "B" }];
myFunc(arrayOfSomeTypes); // okay

Okay, hope that helps. Good luck!

Link to code

like image 119
jcalz Avatar answered Apr 28 '23 19:04

jcalz