如何在TypeScript中提取Angular类的@Input装饰属性类型?
在Angular 14+TypeScript中提取@Input属性类型的类型工具实现
方案一:利用Angular内部元数据类型(自动提取)
该方案依赖Angular内部组件声明类型,可自动从组件类中提取所有被@Input修饰的属性类型,无需额外手动标记:
import { ɵɵComponentDeclaration } from '@angular/core'; // 提取组件的输入属性键名 type ComponentInputKeys<T> = T extends { ɵcmp: ɵɵComponentDeclaration<any, any, any, infer Inputs> } ? keyof Inputs : never; // 最终类型工具:仅保留@Input修饰的属性及其类型 type MyType<T> = { [K in ComponentInputKeys<T>]: T[K]; };
使用示例
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-date-column', template: '<div></div>' }) export class DateColumnComponent { @Input() data!: string | Date; @Input() num!: number; // 非Input属性不会被提取 isActive!: boolean; } // MyType<DateColumnComponent> 等价于 { data: string | Date; num: number } type DateColumnInputs = MyType<DateColumnComponent>;
注意:
ɵɵComponentDeclaration是Angular内部API,当前版本稳定,但未来版本可能存在变更,需留意Angular更新日志。
方案二:手动标记+类型过滤(无内部API依赖)
若不想依赖内部API,可通过给Input属性添加类型标记的方式实现提取,兼容性更强:
// 定义标记类型,用于标识Input属性 type InputMarked<T> = T & { __isInput?: never }; // 类型工具:过滤出带有标记的属性 type MyType<T> = { [K in keyof T as T[K] extends InputMarked<any> ? K : never]: T[K]; };
使用示例
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-date-column', template: '<div></div>' }) export class DateColumnComponent { // 给Input属性添加标记 @Input() data!: InputMarked<string | Date>; @Input() num!: InputMarked<number>; // 非Input属性不添加标记,不会被提取 isActive!: boolean; } // MyType<DateColumnComponent> 等价于 { data: string | Date; num: number } type DateColumnInputs = MyType<DateColumnComponent>;
内容的提问来源于stack exchange,提问作者ertucode
相关产品推荐
相关产品推荐

