Y
Y
yarnstart2020-06-02 02:02:53
typescript
yarnstart, 2020-06-02 02:02:53

How does the construction type t = {...}[keyof T] work?

Code example:

The code

type user = {
    id: number,
    name: string,
};

type getUserKeysWithoutNumberType<T> = {
    [key in keyof T]: T[key] extends number ? never : T[key];
}[keyof T];

const wtf: getUserKeysWithoutNumberType<user> = 'name';



Interested in the construction {...}[keyof T], is there a description of its work somewhere? In this case, it selects keys from the object whose values ​​are not equal to never, where can I read more about this?
And what is this construction {...}[...] ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-06-02
@yarnstart

The usual access by key, as in javascript, what's not clear here?

const foo = {
  bar: 1
};
foo['bar'] // 1
const baz = {
  qux: 2
}['qux']; // 2
Typescript in working with types is no different here:
type user = {
    id: number,
    name: string,
};
type id = user['id']; // number
type userKeys = keyof user; // 'id' | 'name'
type userTypes = user[keyof user]; // number | string
the type neveris simply not taken into account:
number | string | never- the same as number | string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question