객체에 나머지 매개 변수를 입력하는 방법

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

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

테스트 함수에서 주석 인수가 나타날 것이라고 확신합니다. 다른 인수의 경우 속성은 동적 일 수 있지만 값은 부울 유형입니다.

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

이 상황을 고려할 때 데이터를 올바르게 입력하려면 어떻게해야합니까? 나는 이와 같은 것을 시도했지만 잘못된 것 같습니다.

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

답변

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

몇 가지 해결 방법을 제안 할 수 있습니다.

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

함수 본문 외부에 잘 입력되었지만 data.comments올바르게 입력하려면 함수 본문에 약간의 축소를 추가해야합니다.