I have a use case that I thi...">

Typescript Select <> type failing: argument of type "foo" is not assigned to parameter of type "Pick <Bar", "foo">

I have a use case that I think would be ideal for Typescript Select Types .

Here's an example:

interface CreditCard {
  name: string;
  year: number;
  expired: boolean;
}

function setValue(key: keyof CreditCard, value: Pick<CreditCard, typeof key>) {
  // do stuff...
}

      

However, when I try to call this function:

setValue("name", "rick");

      

Typescript (2.3.4) gives the following error:

error TS2345: Argument of type '"rick"' is not assignable to parameter of type 'Pick<CreditCard, "name" | "year" | "expired">'.

      

Also, I don't have an instance CreditCard

available to be passed as an argument, so changing the function to accept CreditCard

as the third parameter is not possible in my use case.

+3


source share


1 answer


Pick<Obj, Props>

creates a type that looks like Obj

with only the properties specified Props

, whereas your example is trying to use it to get the type of a single property, which should be done like this:CreditCard[KeyType]

Your setValue function should look like this:



function setValue<K extends keyof CreditCard>(key: K, value: CreditCard[K]) {
  // do stuff...
}

      

You are setting the generic type K, which is a string literal for one or more keys CreditCard

. Then you use that type to capture the type of the property CreditCard

. When a function is called, the type system will narrow K

it down as much as possible and use it to define a specific type for the argument value

.

+5


source







All Articles