2

I am defining a api for a typescript frontend/backend application.

Now I want to write an interface that is allowed to contain all available keys defined in an other interface, prefixed with 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

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

1
  • 2
    You can do it with mapped types type FilteredRequest<T> = { [key in keyof T]: any; } or using Record: type FilteredRequest<T> = Record<keyof T, any> Commented May 10, 2019 at 8:28

2 Answers 2

2

Unfortunately this is not possible in the current (3.4.5) version of Typescript.

This feature is being debated on github issue.

Sign up to request clarification or add additional context in comments.

Comments

1

Since version 4.1.0, this is now possible by combining template literal types and mapped type 'as' clauses. See the PR for more info.

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

type FilteredRequest<T> = {
  // `& string` excludes `number` and `symbol` properties
  [K in keyof T & string as `filter.${K}`]: T[K];
}

type FilteredUserRequest = FilteredRequest<User>
//    => type FilteredUserRequest = { "filter.firstname": string; "filter.lastname": string; }

Playground link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.