Answer the question
In order to leave comments, you need to log in
How does the construction type t = {...}[keyof T] work?
Code example:
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';
Answer the question
In order to leave comments, you need to log in
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 never
is simply not taken into account: number | string | never
- the same as number | string
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question