[英]Ensure that generic type only has primitive properties in 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). 我有一个采用通用类型的函数,并且我需要确保该类型是JSON可序列化的(也就是仅原始属性)。
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: 我的尝试是为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)
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 . (即SomeType
不允许您随意添加foo
属性,但是当然可以使用JSONable
。此问题在现有的github问题中进一步描述。
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. 所以我知道上面的方法并没有真正起作用,但是问题仍然存在,我需要一些可靠的方法来确保泛型类型是JSON可序列化的。 Any ideas? 有任何想法吗?
Thanks in advance! 提前致谢!
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: 我可能会在此处继续进行操作(在没有修复或更改接口中隐式索引签名周围的潜在问题的情况下)的方式将是将所需的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;
So AsJson<T>
should be equal to T
if T
is a valid JSON type, otherwise it will have never
in its definition somewhere. 因此,如果T
是有效的JSON类型,则AsJson<T>
应该等于T
,否则它将never
AsJson<T>
其定义中。 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
. 要求将thing
与T
(与您推断出T
) 相交,并与AsJson<T>
相交 ,后者将AsJson<T>
添加为对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! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.