简体   繁体   English

确保泛型类型在Typescript中仅具有原始属性

[英]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 . 要求将thingT (与您推断出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! 祝好运!

Link to code 链接到代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 typescript:具有基本类型约束的泛型类型 - typescript : generic type with primitive types constrain 为什么 typescript 不能确保在 React 中添加额外属性的通用高阶组件中的类型安全? - Why typescript does not ensure type safety in a generic higher order component that adds additional properties in React? Typescript:允许泛型类型只是具有&#39;string&#39;属性的对象 - Typescript: allow a generic type to only be an object with 'string' properties TypeScript,具有条件属性的通用类型 - TypeScript, generic type with conditional properties 通用打字稿类型定义包括。 原始类型 - Generic typescript type definition incl. a primitive type 确保泛型类型具有特定属性 - Ensure generic type has certain property Typescript - 声明仅具有单一类型属性的 object? - Typescript - declaring object that only has properties of a single type? 打字稿 - 确保泛型属性存在于具有描述性错误的泛型类型上 - Typescript - Ensure Generic Property Exists On Generic Type With Descriptive Error 一种类型定义,用于覆盖原始类型和泛型类型的属性,而无需合并 - One type definition to cover properties of primitive and generic types without unioning Typescript-用于派生相同类型但没有未定义属性的泛型 - Typescript - Generic for deriving the same type but with no properties undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM