Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

264
Vistas
Typescript - How to make values to equal the keys of an object?

I want to type an object where the key and value are the same:

const myObj = {
    FOO: 'FOO',
    BAR: 'BAR'
};

I tried setting up typeof with myObj, and with the key:

const actions: { [x: string]: x } = { // 'x' refers to a value, but is being used as a type here. Did you mean 'typeof x'?
    set: 'set1'
}

const actions: { [x: string]: typeof x } = {
    set: 'set1'  // doesn't trigger
}

const actions: { [p: string]: keyof typeof actions } = {
    set: 'set' // Type 'string' is not assignable to type 'never'.
}

type K = 'set' | 'set2';
const actions: { [p in K]: K } = { // triggers missing set2
    set: 'set1' // doesn't trigger
}

Is there a way I can make sure the key and value match all the time? TIA!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can do this by creating a helper function that takes in your object then does a TypeScript check on it by generating extra parameters that would make your code fail if the given object does not pass our same key/value law.

// basically, we create an extra parameter when the object is not valid
function createSamePairedObject<T extends Readonly<Record<PropertyKey, PropertyKey>>>(obj: T, ..._lockParams: T extends { [K in keyof T]: K } ? [] : ["INVALID_PAIRED_OBJECT"]): T {
  return obj as any;
}

// PASS
const a = createSamePairedObject({ // { readonly a: "a" }
  a: "a",
} as const);

// FAIL - "b" != "bb"
const b = createSamePairedObject({
  a: "a",
  b: "bb",
} as const);

// FAIL - not const object
const c = createSamePairedObject({
  [5]: 5,
});

// PASS
const d = createSamePairedObject({
  [5]: 5,
} as const);

TypeScript Playground Link

about 4 years ago · Juan Pablo Isaza Denunciar

0

I got it after playing with for a while:

type K = 'set' | 'set2';
const actions: { [p in K]: p } = { // note that I am using p instead of K from the question
    set: 'set1'
}

With this setup I get the following errors:

TS2741: Property 'set2' is missing in type '{ set: "set"; }' but required in type '{ set: "set"; set2: "set2"; }'.

TS2322: Type '"set1"' is not assignable to type '"set"'.

And following is what makes it happy:

type K = 'set' | 'set2';
const actions: { [p in K]: p } = {
    set: 'set',
    set2: 'set2'
}

UPDATE: This works if you have a known list of keys, but if you have an unknown list of keys or to match any key to its value, please follow @sno2 's answer

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda