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

179
Vistas
Replace Array.prototype.includes() with a method that does not return a boolean

I have a function in Typescript in which, from a string, it returns the key of the object that contains that variable.

I'm using Array.prototype.includes() to check that the variable exists, this can return true or false, so typing the resulting variable as a string gives me a typing error.

This is the error:

Type 'unknown' cannot be assigned to type 'string'

This is my function:

let testData = {
  data1: ['CAR','PLANE'],
  data2: ['COUNTRY','CITY']
};

let asset = 'car';

function resKey(asset) {

  let res = Object.keys(testData).find(key => {
    const value = testData[key]
  
    return value.includes(asset.toUpperCase())
  })

  return res

}

console.log(resKey(asset));

I'm only going to pass it values that are in the object, so I don't need to check if it exists.

My problem: how can I modify the function so that it only returns the key without the need to check if it exists?

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

0

As I noted in the comments you can make your current function Typescript friendly by giving it some type annotations.

Alternatively you can avoid the find() by creating a Map of the testData and just retrieving the key by value directly. Keep in mind that if there are duplicate values between different asset arrays this will return the key of the last instance (as opposed to find() which will return the key of the first instance).

let testData = {
  data1: ['CAR', 'PLANE'],
  data2: ['COUNTRY', 'CITY']
};

let asset = 'car';

function resKey(asset) {
  const resMap = new Map(Object.entries(testData).flatMap(([k, v]) => v.map(a => [a, k])));
  
  return resMap.get(asset.toUpperCase());
}

console.log(resKey(asset));

To avoid creating a new Map on every call of the function you might employ a little currying.

function resKeyFactory(data) {
  const resMap = new Map(
    Object.entries(data)
      .flatMap(([k, v]) => v.map(a => [a, k]))
  );

  return (asset) => resMap.get(asset.toUpperCase());
}

const
  testData = {
    data1: ['CAR', 'PLANE'],
    data2: ['COUNTRY', 'CITY']
  },
  asset = 'car',
  resKeyTestData = resKeyFactory(testData);

console.log(resKeyTestData(asset));
console.log(resKeyTestData('city'));

Typescript requires a high enough target to accept flatMap playground.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could use Object.entries() and find().

let testData = {
  data1: ['CAR', 'PLANE'],
  data2: ['COUNTRY', 'CITY']
};

function resKey(data, asset) {
  return Object.entries(data).find(([_, v]) => {
    return v.includes(asset.toUpperCase())
  })?.[0] || "no key found";
}

console.log(resKey(testData, "car"));
console.log(resKey(testData, "something"));
console.log(resKey(testData, "city"));

If you want to type, it would look something like this.

interface IData {
  data1: string[];
  data2: string[];
}

let testData: IData = {
  data1: ['CAR', 'PLANE'],
  data2: ['COUNTRY', 'CITY']
};

function resKey(data: IData, asset: string): string {
  return Object.entries(data).find(([_, v]) => {
    return v.includes(asset.toUpperCase())
  })?.[0] || "no key found";
}
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