1

I need simple type checking based on object property which I'd like to use like this:

type User = { id: string, name: string }
sort<User>("name");

where Intellisense offers me "name" or "id" for input or shows "error" if anything else is entered.

With my current implementation property is not of type string, although I'm able to pass only string value.

sort<T extends { [key: string]: any }>(property: keyof T) {
    // how can I make 'property' string ???
    // required API object is e.g. { property: "Id", desc: true }
}

Here is playground.

6
  • 1
    property type is union of keys from T and it looks fine. Why do you want to have property with type string? Commented Sep 25, 2019 at 11:22
  • I've edited my question. Because I need only single property in that method. keyof T is not requirement, its the way I've currently implemented it. Commented Sep 25, 2019 at 11:32
  • hm... Why didn't you define sort<T extends { [key: string]: any }>(property: string) { this way ? Commented Sep 25, 2019 at 11:40
  • Because I would have any Intellisense telling me to pass only property names of T, which is whole point of question. Commented Sep 25, 2019 at 11:48
  • I'm not sure I understand you. But you can try this sort<T extends { [key: string]: any }>(property: keyof T | string) { Commented Sep 25, 2019 at 11:52

1 Answer 1

3

Even though your constraint has a string indexer in actual fact the keyof T could still be a number so keyof T would end up being string | number

You can use Extract to arrow to just strings:


type Custom = {
  property: string, //ok 
  desc: boolean
}

function sort<T>(property: Extract<keyof T, string>): Custom {
    return {
      property: property,
      desc: false
    }
}

type User = { id: string, name: string }
sort<User>("name");

play

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

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.