G
G
Grishalovesfront2021-09-20 18:32:50
typescript
Grishalovesfront, 2021-09-20 18:32:50

How to make a value object generic?

Good day to all! I'm learning typescript while I'm just learning and trying myself, in general, typing is something new for me, and I have a question.

There is such a code

type myObjectTypes = {
 name:  string;
 number:  number
}

type myObjectKeys = keyof myObjectTypes;

const myObject: myObjectTypes = {
 name: 'Alex',
 number: 1337
}


const myFunction = (key:  myObjectKeys): <???> => myObject[key as string];


Actually just a function that will return the value of the object by key. And the question is what should I write in <???> so that I would know what type will be returned by this key, something like
keyof myObjectTypes, only for its value by the key that I pass. I can't figure it out :)
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2021-09-20
@Grishalovesfront

Link

const myFunction = <K extends keyof MyObjectTypes>(key: K): MyObjectTypes[K] => myObject[key];

essence: we pass to myFunction a value that can be only one of the keys of MyObjectTypes (restriction extends keyof MyObjectTypes ) a specific K
is determined by this passed value - the narrowing of the type to one key. well and further MyObjectTypes[K] on these data already precisely knows the type.

W
WbICHA, 2021-09-20
@WblCHA

First, - this is a mistake, it should be simple . Secondly, in addition to what Alexandroppolus indicated in his answer, you can not specify the return type at all, the TC will determine it himself. [key as string][key]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question