typescript - 如何从接口(interface)仅获取数组或其他类型?

标签 typescript types interface

我有一个这样的界面:

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; };

最佳答案

您可以声明映射类型并重新映射键 ( 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[] }

TypeScript playground

关于typescript - 如何从接口(interface)仅获取数组或其他类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71931430/

相关文章:

javascript - RxJS - 发生错误时可观察对象未完成

python - 如何用 Python 伪造类型

python - 在 python 中查找类型 - TypeError 'unicode' 对象不可调用

android - 安装 Android USB 驱动程序 - 没有发生

angular - 找不到导出接口(interface)的名称

typescript - 如何从 Angular 2 中的日期类型中减去一年?

typescript - Redux 工具包不更新数组对象的数组

typescript - 获取 TypeError : numeral_1. 默认值不是值转换器中的函数

scala - => 位于 [] 内是什么意思?

java - 使用 GlassFish 4 的 JNDI 独立应用程序的 EJB 3.1 问题