Javascript Typescript如何在对象中键入其余参数
在test函数中,我确信会出现comment参数,其中对于其他参数,属性可能是动态的,但值将是布尔类型Javascript Typescript如何在对象中键入其余参数,javascript,typescript,Javascript,Typescript,在test函数中,我确信会出现comment参数,其中对于其他参数,属性可能是动态的,但值将是布尔类型 function test(data){ console.log(data) } test({comments: 'hi', eat: true, sleep: true}) 考虑到这种情况,我应该如何正确地键入数据? 我试过这样的方法,但似乎不对 test({comments: 'hi', drink: true, sleep: true}) 我可以向您建
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})
函数测试(数据:{comments:unknown}&{[key-in-keyof-T]:键扩展了“comments”?字符串:boolean}){
const comments=data.comments作为字符串;
控制台日志(注释);
console.log(data.eat);
console.log(data.sleep);
}
测试({注释:“hi”});//作品
测试({注释:“嗨”,eat:true});//作品
测试({comments:true});//不起作用
测试({注释:5});//不起作用
测试({comments:“hi”,eat:“true”});//不起作用
测试({注释:“hi”,eat:5});//不起作用
它在函数体之外输入得很好,但在函数体中输入
数据。正确的注释
,您应该添加一些缩小范围。是。我只是想安慰一下。编辑的问题是这样一个问题,“我给参数data
赋予什么类型,它应该是一个对象,至少有一个名为comments
,类型为string,但可能有很多我不关心的其他属性”?是的。。我不关心其他属性..如果您不关心其他属性,那么type DataType={comments:string;[key:string]:unknown;}代码>将起作用。对,对,你的问题确实不同(而且很酷)。看起来交叉口类型有潜力,但不足。更多信息请点击此处:。
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