How to restrict typescript's literal expression to accept only available property?

Viewed 91

This is a very simple question.


const foo = {
    "a" :1,
    "b" :2,
    "c" :3
}

const foo2 = {
    "a":1,
    "c":2
}

const foo3:typeof foo2 = {...foo}

Now foo3 has a property called b. But typeof foo2 dose not have property "b", I would like to prevent this. By config typescript.

I know i can solve this problem with object assign, but i can't use object assign in situations where only the type is defined and there is no object.

1 Answers

You can use String literal types and declare the keys you want to have.

E.g.

type aType = 'a' | 'b' | 'c';
const foo: {[key in aType]: number} = {
  'a': 1,
  'b': 2,
  'c': 3 
};

const foo2: {[key in aType]: number} = {
  'a': 1,
  'c': 3 
};

const foo3: typeof foo2 = {...foo}

Now the code above should throw you something like

Property 'b' is missing in type etc.. etc..
Related