typescript - Conversia obiectului într-un tip union


Am o întrebare despre TypeScript. Vreau să creez ceva de genul unei uniuni din valorile unui obiect. Cum pot realiza acest lucru? de exemplu:

const x = {
    x: 1,
    y: 2,
    z: 'a string',
    k: document.createElement('div')
}

const y = (y: the value which exist of x ): boolean => {
  return true
}

Ceva de genul:

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

dar pentru obiecte. Orice sugestii sunt binevenite.

Răspuns #1

Pentru a obține o reuniune a valorilor din tipul unei variabile, poți folosi ValueOf<typeof x>. Pentru exemplul tău, acel tip ar fi string | number | HTMLDivElement

const x = {
    x: 1,
    y: 2,
    z: 'a string',
    k: document.createElement('div')
}
type ValueOf<T> = T[keyof T]; 
const y = (P: ValueOf<typeof x>): boolean => { // p:  string | number | HTMLDivElement
   return true
}

Din comentarii se pare că vrei tipurile literale (1 | 2 | "a string") nu tipurile de bază. Pentru ca acest lucru să funcționeze, trebuie să schimbi tipul lui x pentru a include tipurile literale. Cea mai simplă modalitate de a face acest lucru în 3.4 este să adaugi o afirmație const:

const x = {
    x: 1,
    y: 2,
    z: 'a string',
    k: document.createElement('div')
} as const
type ValueOf<T> = T[keyof T];
const y = (p: ValueOf<typeof x>): boolean => { // p:  1 | 2 | "a string" | HTMLDivElement
    return true
}

Răspunsul #2

Cred că asta este ceea ce ai nevoie:

export const xx = {
    x: 1,
    y: 2,
    z: 'a string',
    k: document.createElement('div')
};

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

type XValues = ValueOf<typeof xx>;