0

I'm providing a public Interface to my data, but for performance and memory reasons I want to use an Object and definitely not a Class. There's no code on the Interface, it is purely a data structure.

I want to be able to declare my Object as using the Interface so that if I change the Interface it'll show up as an error and doesn't get missed.

interface DataStructure { key1: string; key2: number; key3: boolean; key4: null; } const defaultData: {[key: string]: PropertyDescriptor} = { key1: {writable: true, enumerable: true}, key2: {writable: true, enumerable: true}, key3: {writable: true, enumerable: true} }; var myData = Object.create(null, defaultData); 

I want this to report an error for missing key4 in the defaultData Object, but can't quite figure out how right now.

(This is needed due to potentially tens of thousands of objects needing the same structure, and not wanting to waste GC on them when it's easier to just re-use them - also wanting simply Map stores, so no need for the Object prototype chain.)

6
  • Can you not implement a minimal version of the interface? Kinda like class SimpleDataStructure implements DataStructure?
    – Icepickle
    CommentedJul 25, 2017 at 16:15
  • Have you tried var myData: DataStructure = Object.create(null, defaultData);?CommentedJul 25, 2017 at 16:25
  • @Icepickle. This is a bit beyond my level of expertise with Typescript ATM.. But I believe the inclusion of PropertyDescriptor implies OP is doing something like creating an annotation / Decorator, that can be used for things like Reflection.
    – JGFMK
    CommentedJul 25, 2017 at 16:33
  • @Icepickle Unfortunately a class would still be sitting on top of Object, and I need it to sit on null instead.
    – Rycochet
    CommentedJul 25, 2017 at 16:56
  • @MikeMcCaughan That wouldn't throw an error, as Object.create returns any - so there's nothing for it to complain about ;-)
    – Rycochet
    CommentedJul 25, 2017 at 16:57

1 Answer 1

1

I think that this is what you're looking for:

const defaultData: {[K in keyof DataStructure]: PropertyDescriptor} = { ... } 

The compiler will then compile saying:

Type '{ key1: { writable: true; enumerable: true; }; key2: { writable: true; enumerable: true; }; key3:...' is not assignable to type '{ key1: PropertyDescriptor; key2: PropertyDescriptor; key3: PropertyDescriptor; key4: PropertyDes...'.

Property 'key4' is missing in type '{ key1: { writable: true; enumerable: true; }; key2: { writable: true; enumerable: true; }; key3:...'.

1
  • Doh - I'd missed out the K in before it - hence why I couldn't get it to work - thanks!
    – Rycochet
    CommentedJul 25, 2017 at 16:54

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.