0

This might not be possible due to the difference between Types and Values. But thought it worth asking.

interface Entity {
  id: string;
  code: number;
}

const convert = <E extends Entity>( presentable:E ): Entity => {
  // Is it possible to remove keys in 'presentable' that do not exist in `Entity`?
  return presentable
}

// should return { id: '10', code: 100 }
const converted1 = convert({ id: '10', code: 100 }); 

// should return { id: '5', code: 200 }
const converted2 = convert({ id: '5', code: 200, label: 'My label', name: 'My name' }); 

I want to remove "presentation" properties before sending in a HTTP payload. Type "Entity" can change to different interfaces, so I don't want to check for specific keys.

Maybe there is a way to enforce keys as an argument that don't match both interfaces? But I wouldn't know how to say:

keyof E and not keyof Entity. ?

Ewan
  • 378
  • 3
  • 14
  • Use `Omit<…>` built-in utility type: `Omit` – Parzh from Ukraine Aug 17 '23 at 08:54
  • @ParzhfromUkraine that doesn't change any values. – VLAZ Aug 17 '23 at 08:54
  • Actually modifing an object is a runtime operation and at runtime type informatioin is transpiled away so I don't think this is possible unless you have a hardcoded list of allowed keys somewhere – apokryfos Aug 17 '23 at 08:55
  • Oh, it's definitely not possible then. Any TypeScript-specific information is removed at runtime, so JavaScript can't interact with it. Maybe `reflect-metadata` can help, but I'm not sure – Parzh from Ukraine Aug 17 '23 at 08:56
  • Yeah, so I realise it's not possible without providing a list of keys. So I was thinking of enforcing the keys that are not in both interfaces. – Ewan Aug 17 '23 at 08:59
  • There are some TS gymnastics you can make to make sure you have an array of keys for `Entity` and `Entity` only, then return an object with just those keys. However, it's probably an overkill for most use-cases. I'd just create a simple transforming function which would be tied to `Entity` (probably in the same module) and some unit tests to ensure it works correct. Changing the interface should also force the developer to update the function and the tests. Even then, that might be too much - in the BE you can just deserialising into a type that doesn't have presentation properties. – VLAZ Aug 17 '23 at 09:04
  • Closed is as not possible. Will create another question for another approach. – Ewan Aug 17 '23 at 09:18

0 Answers0