0

Say I have the following object:

const obj = {
  foo: "bar",
  hello: "world",
}

and the following object processing function:

const process = (obj) => {
  const processedObj = {}
  for (const key in obj) {
    processedObj[`--${key}`] = obj[key]
  }
  return processedObj
}

How can I type key argument to only accept processed keys that start with --?

const processedObj = process(obj)
const getValue = (key) => {
  return processedObj[key]
}

Trying to programatically convert JS object properties to CSS variables so that Visual Studio Code IntelliSense feature suggests getValue("--foo") when typing getValue("--f").

sunknudsen
  • 6,356
  • 3
  • 39
  • 76
  • You want things that are keys of the type of the object, so... `keyof typeof obj`? – jonrsharpe May 27 '22 at 13:02
  • Now it looks like you want https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html. But _are_ you using TypeScript? Nothing you've shown actually has any type information - maybe that would be a good starting point? – jonrsharpe May 27 '22 at 13:13
  • @jonrsharpe I am using TypeScript… used plain JS to show use case with as little code as possible. – sunknudsen May 27 '22 at 13:17
  • But as you've already seen with the answer below, not giving enough context means you get answers that don't actually address your problem. If you're asking about TS behaviour, _types_ seem like a pretty obvious thing to include. And _show_ your research; you could have included the linked question when asking so you didn't get told something you already knew. – jonrsharpe May 27 '22 at 13:19
  • @jonrsharpe Trying my best here… sorry for not making question clear enough. I updated question as quickly as I could when it appeared misleading. – sunknudsen May 27 '22 at 13:20
  • There's more or less exactly what you're looking for in https://www.typescriptlang.org/docs/handbook/2/mapped-types.html – jonrsharpe May 27 '22 at 13:37

1 Answers1

2

You can use keyof typeof:

const func = (key : keyof typeof obj) => {
  return obj[key]
}

Example

Elidor00
  • 1,271
  • 13
  • 27