0

I have this code:

type Foo = {
  fiz: 'baz',
  bar: 'biz'
}

const foo: Partial<Foo> = {}

Essentially, the type will change a lot, and I want to do smth like this:

Object.keys(Foo).map(key=>{
  foo[key] = null;
})

But that's obviously impossible. Is there a way to make it work dynamically? Or am I stuck with typing each key dynamically?

Link to playground

Alex Ironside
  • 4,658
  • 11
  • 59
  • 119
  • `Foo` is a type not an object. JS doesn't have any knowledge of types, so you'll likely need to use an object creator of some kind. Like a factory, or class. – evolutionxbox Feb 08 '22 at 17:05
  • You can do it backwards by defining an object named `Foo` and driving the type `Foo` from it, like [this](https://tsplay.dev/wgX89N). If that works for you I can write up an answer. But your example code has a few weird things (`null` is not generally assignable to an optional property if you've got strict null checks; `Object.keys()` cannot be guaranteed to give only known keys, see https://stackoverflow.com/q/55012174/2887218, etc) so it would be nice to clear those up before proceeding with an answer. Good luck! – jcalz Feb 08 '22 at 17:11
  • Well, I'm trying to make an object with keys from the type. With any value, I just want to make sure the keys are there, dynamically, based on the type. I will iterate over the object keys later – Alex Ironside Feb 08 '22 at 17:44
  • You can't make an object from a type with pure TypeScript; [types are erased](https://www.typescriptlang.org/docs/handbook/2/basic-types.html#erased-types). You can do it backwards and make a type from an object; that's the same amount of work and has the advantage of being possible. Would you like an answer explaining why what you want is impossible and suggesting that you do it in reverse instead? – jcalz Feb 09 '22 at 03:24

1 Answers1

0

Im not entirely sure what your goal is. Are you trying to ensure your objects will always start with all keys, even if they have no values?. I dont think this would be possible based on the type due to the type not existing at runtime. Instead you could create an object of that type with all keys and use the spread operator {...foo} to create other objects with those keys (Example).

domi
  • 362
  • 4
  • 6