[英]Typescript narrow {[key: string]: T} to an object literal
I would like to write a function that enforces an object to be of type {[key: string]: T} and returns an object literal of the provided argument.我想写一个 function 强制 object 的类型为 {[key: string]: T} 并返回 object 提供的参数的文字。
For example, if I have the following type A:例如,如果我有以下类型 A:
interface A{
a: string,
b: number
}
I would like to have a function B
that takes an object with properties, all of type A
, and returns the provided object with properties accessible using dot notation.我想要一个 function
B
,它接受一个带有属性的 object ,所有类型A
,并返回提供的 object ,其属性可使用点表示法访问。
My current function is this:我目前的 function 是这样的:
const B = (arg: {[key: string]: A}) => arg;
But when I call it like so:但是当我这样称呼它时:
const c = B({
a: {
a: "test",
b: 1
}
})
I can't access the property a
with dot notation, like c.a
.我无法使用点符号访问属性
a
,例如c.a
。
How can I make it so that function B returns a literal type based on what it receives so that I can access properties with dot notation?如何使 function B 根据接收到的内容返回文字类型,以便我可以使用点符号访问属性?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.