简体   繁体   English

带通用键的Typescript接口

[英]Typescript interface with keys of Generic

I am defining a api for a typescript frontend/backend application. 我正在为打字稿前端/后端应用程序定义一个api。

Now I want to write an interface that is allowed to contain all available keys defined in an other interface, prefixed with filter. 现在,我想编写一个允许包含另一个接口中定义的所有可用键的接口,并以filter.为前缀filter.

Lets say I have a user interface 可以说我有一个用户界面

interface User {
  firstname: string;
  lastname: string;
}

A User request can be filtered, so my general Request ist extended with FilteredRequest 可以过滤用户请求,因此我的常规请求扩展了FilteredRequest

interface FilteredRequest<T> {
  [key: 'filter.' + keyof T]: any;
}

Is this possible with typescript? 打字稿可以吗?


Ok because this is not possible right now. 好的,因为目前无法实现。

Also not prefixing the key with someting does not work 同样不给键加前缀不起作用

interface FilteredRequest<T> {
  [key: keyof T]: any;
}

An index signature parameter type must be 'string' or 'number'.ts(1023)

But keyof is designed to return a string or number 但是keyof旨在返回stringnumber

Unfortunately this is not possible in the current (3.4.5) version of Typescript. 不幸的是,在当前(3.4.5)版本的Typescript中这是不可能的。

This feature is being debated on github issue. 这个功能正在github问题上进行辩论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM