Typescriptオブジェクトに残りのパラメータを入力する方法
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
正しく入力するには、絞り込みを追加する必要があります。