gpt4 book ai didi

typescript - 确保泛型类型在 Typescript 中只有原始属性

转载 作者:行者123 更新时间:2023-12-04 11:55:43 25 4
gpt4 key购买 nike

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

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

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)

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

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

提前致谢!

最佳答案

我可能会在这里进行的方式(在没有修复或更改 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;

所以 AsJson<T>应该等于 T如果 T是一个有效的 JSON 类型,否则它会有 never在它的定义某处。然后我们可以这样做:
declare function myFunc<T>(thing: T & AsJson<T>): T;

这需要 thingT (为您推断 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)类型已被接受:
interface SomeType {
id: string;
name: string;
}

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

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

Link to code

关于typescript - 确保泛型类型在 Typescript 中只有原始属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57858862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com