简体   繁体   中英

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})

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM