如何仅从接口获得数组或其他类型?

发布于 2025-01-22 11:44:01 字数 423 浏览 2 评论 0原文

我有这样的接口:

interface Car {
  model: string;
  owners: string[];
}

我只想获得数组属性:

type NewCar = OnlyArrays<Car>

这将等于:

type NewCar = {
  owners: string[];
}

键入并不重要,例如数组。

我尝试了此代码,但它不起作用:

function getCar<T = Car>(id: string): { [P in keyof T]: T[P] extends array ? string[] : string; };

I have an interface like that:

interface Car {
  model: string;
  owners: string[];
}

And I want to get only array properties:

type NewCar = OnlyArrays<Car>

And this will be equal to:

type NewCar = {
  owners: string[];
}

Type it's not important, array just for example.

I've tried this code but it doesn't work:

function getCar<T = Car>(id: string): { [P in keyof T]: T[P] extends array ? string[] : string; };

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初心 2025-01-29 11:44:01

您可以声明映射类型并重新重新键( docs )仅包含该值扩展数组的那些键:

type OnlyArrays<T> = {
  [K in keyof T as T[K] extends Array<infer _> ? K : never]: T[K]
}

type NewCar = OnlyArrays<Car>
// type NewCar = { owners: string[] }

You can declare a mapped type and remap the keys (docs) to include only those keys for which the value extends an array:

type OnlyArrays<T> = {
  [K in keyof T as T[K] extends Array<infer _> ? K : never]: T[K]
}

type NewCar = OnlyArrays<Car>
// type NewCar = { owners: string[] }

TypeScript playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文