#What is the purpose of adding a [T] at the end of an Object?

8 messages · Page 1 of 1 (latest)

odd hatch
#

I have this TS code and am confused on the last bit of it:

type LookUp<U extends {type: PropertyKey}, T extends PropertyKey> = {
  [P in T] : U extends {type: T} 
  ? U
  : never
  }[T] //What does this do?

This code is from the challenge: https://github.com/type-challenges/type-challenges/blob/main/questions/00062-medium-type-lookup/README.md

GitHub

Collection of TypeScript type challenges with online judge - type-challenges/README.md at main · type-challenges/type-challenges

ruby blade
#

It accesses the T key on the returned object type, so the type is the value of the object at property T

opaque pumice
#

This is essentially:

// Takes an object type, converts it into a union of values
type Values<T> = T[keyof T];
#

(T is equivalent to keyof /* object type */ because the object type is defined as {[P in T]: /* something */}

ruby blade
#

hmm

#

I'm wrong on this, this didn't behave the way I expected on my first read

type LookUp<U extends {type: PropertyKey}, T extends PropertyKey> = {
  [P in T] : U extends {type: T} ? U : never 
}[T]

type Values<T> = T[keyof T];

type X = LookUp<{type: 'hello', x: 1}, 'hello'> // { type: 'hello'; x: 1; }
type Y = Values<{type: 'hello', x: 1}> // "hello" | 1
opaque pumice
#

Yeah, sorry I was saying that the [T] bit at the end was equivalent to wrapping the rest of the expression in Values, not that the LookUp was somehow equivalent.

ruby blade
#

ahh, was trying to understand it myself