Maszynopis, jak wpisać pozostałe parametry w obiekcie

Nov 26 2020
  function test(data){
      console.log(data)
  }

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

W funkcji testowej jestem pewien, że pojawi się argument komentarza, gdzie podobnie jak w przypadku innych argumentów właściwości mogą być dynamiczne, ale wartość będzie typu boolowskiego,

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

biorąc pod uwagę tę sytuację, jak poprawnie wpisać dane? Próbowałem czegoś takiego, ale wydaje się to złe

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

Odpowiedzi

1 НиколайГольцев Nov 26 2020 at 17:55

Mogę zasugerować jakieś obejście:

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

Wpisywał się dobrze poza treścią funkcji, ale w treści funkcji, aby data.commentspoprawnie pisać , należy dodać pewne zawężenie.