Thiago Pereira Maia
Thiago Pereira Maia

Reputation: 623

Force argument object with a certain key

This seems like something fairly simple, but I have tried searching it multiple ways and couldn't find an answer.

I want to specify a type for an argument that allows any objects that contain a certain key, like this:

type Action = {type : string};
function reducer(state : object, action : object extends Action) {
    ...
};

Something like this, but this syntax doesn't work. That is, I want the action argument only to accept objects that contain the key "type" that is a string. If I just do this:

function (state : object, action : {type : string}) {...};

The function only accepts objects that only have the key "type". How can I achieve this?

Thanks in advance.

Upvotes: 0

Views: 239

Answers (1)

DemiPixel
DemiPixel

Reputation: 1881

You can use a generic for this:

function testFn<T extends { type: string }>(obj: T) {
  return obj;
}

testFn({ a: 2, type: 'hey' }); // Fine
testFn({ type: 'hello' }); // Fine

testFn({ a: 2 }); // Type error
testFn({ a: 2, type: 3 }); // Type error

Upvotes: 1

Related Questions