【问题标题】:Ensure that generic type only has primitive properties in Typescript确保泛型类型在 Typescript 中仅具有原始属性
【发布时间】:2020-01-11 12:10:04
【问题描述】:

我有一个采用泛型类型的函数,我需要确保该类型是 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 当然可以。此问题在此existing github issue 中有进一步描述。

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

提前致谢!

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我可能会在这里进行的方式(在没有修复或更改 underlying issue around implicit index signatures in interfaces 的情况下)将您所需的 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;
    

    如果T 是一个有效的JSON 类型,那么AsJson&lt;T&gt; 应该等于T,否则它的定义中会包含never。然后我们可以这样做:

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

    要求thingT(为您推断T相交AsJson&lt;T&gt;,这将AsJson&lt;T&gt; 添加为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
    

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

    Link to code

    【讨论】:

    • 您先生,真是个天才!非常简洁的解决方案,它似乎对我来说可以无缝地工作!
    猜你喜欢
    • 2019-05-29
    • 2018-03-05
    • 2019-10-06
    • 2016-05-13
    • 2021-11-12
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多