获取Typescript接口的键作为字符串数组 [英] Get keys of a Typescript interface as array of strings
问题描述
我在Lovefield有很多桌子,他们各自的界面都有他们所拥有的列。
例子:
export interface IMyTable {
id:number;
title:string;
createdAt:Date;
isDeleted:boolean;
}
我想把这个接口的属性名称放在一个像这样的数组中这个:
var IMyTable = [id,title,createdAt,isDeleted];
我不能直接根据接口 IMyTable
创建一个对象/数组,这应该可以解决问题因为我要获取接口名称这些表是动态的。因此,我需要在接口中迭代这些属性并从中获取数组。
如何实现此结果。
从TypeScript 2.3开始(或者我应该说2.4,如2.3中这个功能包含一个错误,已在typescript@2.4-dev中修复,你可以创建一个自定义变换器来实现你想要做的事情。
<实际上,我已经创建了这样一个自定义变换器,它可以实现以下目的。
https://github.com/kimamula/ts-transformer-keys
从'ts-transformer-keys'导入{keys};
interface Props {
id:string;
name:string;
年龄:数量;
}
const keysOfProps = keys< Props>();
console.log(keysOfProps); // ['id','name','age']
不幸的是,定制变换器目前是不那么容易使用。您必须将它们与TypeScript转换API一起使用,而不是执行tsc命令。有问题请求自定义变换器的插件支持。
I've a lot of tables in Lovefield and their respective Interfaces for what columns they have.
Example:
export interface IMyTable {
id: number;
title: string;
createdAt: Date;
isDeleted: boolean;
}
I'd like to have the property names of this interface in an array like this:
var IMyTable = ["id", "title", "createdAt", "isDeleted"];
I cannot make an object/array based on the interface IMyTable
directly which should do the trick because i'd be getting the interface names of the tables dynamically. Hence i need to iterate over these properties in the interface and get an array out of it.
How do i achieve this result.
As of TypeScript 2.3 (or should I say 2.4, as in 2.3 this feature contains a bug which has been fixed in typescript@2.4-dev), you can create a custom transformer to achieve what you want to do.
Actually, I have already created such a custom transformer, which enables the following.
https://github.com/kimamula/ts-transformer-keys
import { keys } from 'ts-transformer-keys';
interface Props {
id: string;
name: string;
age: number;
}
const keysOfProps = keys<Props>();
console.log(keysOfProps); // ['id', 'name', 'age']
Unfortunately, custom transformers are currently not so easy to use. You have to use them with the TypeScript transformation API instead of executing tsc command. There is an issue requesting a plugin support for custom transformers.
这篇关于获取Typescript接口的键作为字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!