如何在 Typescript 泛型中获取数组类型 [英] How to get Type of Array in Typescript generics

查看:39
本文介绍了如何在 Typescript 泛型中获取数组类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的方法:

public select(fieldName: keyof TType)

其中 TType 可以是数组类型.如果是数组类型,fieldName 将正确地为我提供 Array 类型的所有属性名称.

Where TType could be an array type. In case of an array type, fieldName will correctly offer me all the propertynames of type Array.

如果我使用 User[] 类型调用此方法,我想访问 User 的属性而不是 Array.

In case I call this method with a type of User[] I want to get to the properties of User instead of the properties of Array.

有没有办法做到这一点?

Is there any way of how this could be done?

额外问题:有什么办法可以限制 TType 为数组类型?

Extra question: Is there any way to restrict TType to be of an array type?

推荐答案

你绝对可以制作一个 conditional 类型函数,它将数组类型解包到一层深度,然后对结果使用 keyof.例如:

You can definitely make a conditional type function that unwraps an array type up to one level deep, and then use keyof on the result of that. For example:

// unwrap up to one level
type Unarray<T> = T extends Array<infer U> ? U : T;

// your class maybe
declare class Thingy<T> {
  constructor(t: T);
  public select(fieldName: keyof Unarray<T>): void;
}
// your interface maybe
interface User {
  name: string,
  age: number
}

declare const u1: User;
declare const u2: User;
const x = new Thingy(u1);
x.select("name"); // okay
const y = new Thingy([u1, u2]);
y.select("age"); // okay
y.select("push"); // error

这应该可以按您的意愿工作,对于打字,我认为.显然,您还需要有一个有效的实现(并注意,实现中的条件类型通常需要一些类型断言或重载才能使编译器满意……但您似乎在询问类型,而不是实现).

That should work as you want, for the typings, I think. Obviously you also need to have an implementation which works (and note that conditional types in implementations usually require some type assertions or overloads to make the compiler happy... but you seem to be asking about the typings, not the implementation).

至于您的额外问题,是的,您可以将 T 限制为仅数组类型,如下所示:

As for your extra question, yes, you can restrict T to just array types, as follows:

// your class maybe
declare class Thingy<T extends Array<any>> {
  constructor(t: T);
  public select(fieldName: keyof (T[number])): void;
}
// your interface maybe
interface User {
  name: string,
  age: number
}

declare const u1: User;
declare const u2: User;
const x = new Thingy(u1); // error
const y = new Thingy([u1, u2]);
y.select("age"); // okay

请注意,我在这里完全取消了条件类型,因为它更直接.

Note that I did away with the conditional types altogether here because it's more straightforward.

希望有所帮助;祝你好运!

Hope that helps; good luck!

这篇关于如何在 Typescript 泛型中获取数组类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆