sridhar..
sridhar..

Reputation: 2133

Typescript how to type the rest of parameters in object

  function test(data){
      console.log(data)
  }

  test({comments: 'hi', eat: true, sleep: true})

In the test function, I am sure of the comment argument will appear, where as for other arguments, the properties might be dynamic but the value will be of boolean type,

  test({comments: 'hi', drink: true, sleep: true})

considering this situation, how should I correctly type data? I have tried something like this, but it seems wrong

function(data: {data: {comments: string, [key: string]: boolean})

Upvotes: 3

Views: 1460

Answers (1)

I can suggest you some kind of workaround:

function test<T extends {
  [key: string]: any;
}>(data: { comments: unknown } & { [key in keyof T]: key extends "comments" ? string : boolean }) {
  const comments = data.comments as string;
  console.log(comments);
  console.log(data.eat);
  console.log(data.sleep);
}

test({comments: "hi"}); // works
test({comments: "hi", eat: true}); // works
test({comments: true}); // doesn't works
test({comments: 5}); // doesn't works
test({comments: "hi", eat: "true"}); // doesn't works
test({comments: "hi", eat: 5}); // doesn't works

It typed well outside of the function's body, but in function's body to type data.comments correctly you should add some narrowing.

Upvotes: 1

Related Questions