[英]Inferring object property from function parameter
I defined the function我定义了 function
function test<T>(name: string, value: T) {
return {[name]: value};
}
and VSCode displays the return type as {[x: string]: T}
. VSCode 将返回类型显示为
{[x: string]: T}
。 I would like VSCode to complete foo
after typing我希望 VSCode 在输入后完成
foo
test("foo", "bar").
but it doesn't know about foo
because it isn't in the inferred type.但它不知道
foo
因为它不在推断类型中。
I've tried我试过了
function test<T>(name: string, value: T): {[key: name]: T} {
return {[name]: value};
}
but it complains that name
is a variable and not a type.但它抱怨
name
是一个变量而不是一个类型。
How can I achieve that it takes the value of name
and uses it as a type?我怎样才能实现它采用
name
的值并将其用作类型?
My use case is a Vue.js mixin, that I've defined with a factory function so I can easily add similar mixins.我的用例是一个 Vue.js mixin,我用工厂 function 定义了它,所以我可以轻松添加类似的 mixin。
Answering my own question since I've found the solution:找到解决方案后回答我自己的问题:
function bla<T extends string | number | symbol, V>(name: T, value: V) {
return { [name]: value } as { [K in T]: V };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.