4

我有一个采用泛型类型的函数,我需要确保该类型是 JSON 可序列化的(也就是只有原始属性)。

我的尝试是为 JSON 兼容类型定义一个接口,并强制我的泛型扩展此类型:

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)

这里的问题似乎归结为索引签名在打字稿中的工作方式。具体来说,如果一个类型缩小了索引签名允许的可能属性,则它不能扩展具有索引签名的类型。(即SomeType不允许您任意添加foo属性,但JSONable当然可以。此问题在此现有 github 问题中有进一步描述。

所以我知道上面并没有真正起作用,但问题仍然存在,我需要一些可靠的方法来确保泛型类型是 JSON 可序列化的。有任何想法吗?

提前致谢!

4

1 回答 1

9

我可能会在这里进行的方式(在没有修复或更改围绕接口中的隐式索引签名的潜在问题的情况下)将您所需的 json 类型表示为类似于这样的通用约束:

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;

所以AsJson<T>应该等于TifT是一个有效的 JSON 类型,否则它会never在某个地方定义。然后我们可以这样做:

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

这要求thingbe T(为您推断T)与相交AsJson<T>,这将AsJson<T>作为附加约束添加到thing. 让我们看看它是如何工作的:

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

现在您的接口类型被接受:

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

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

好的,希望有帮助。祝你好运!

链接到代码

于 2019-09-09T18:30:05.393 回答