3
  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})
9
  • Yes. i just want to console. Edited the question Commented Nov 26, 2020 at 9:42
  • Is the question, then, "what type do I give to the parameter data, which should be an object with at least one property named comments of type string, but which could have lots of other properties that I don't care about"? Commented Nov 26, 2020 at 9:43
  • Yes.. I dont care about other properties.. Commented Nov 26, 2020 at 9:45
  • If you don't care about the other properties, then type DataType = { comments: string; [key: string]: unknown; }; will work. Ref: stackoverflow.com/a/33860616 Commented Nov 26, 2020 at 9:50
  • 1
    Right, right, your question is indeed different (and pretty cool). Looks like intersection types have potential, but fall short. More info here: github.com/microsoft/TypeScript/issues/20597. Commented Nov 26, 2020 at 10:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.