简体   繁体   English

Typescript 窄 {[key: string]: T} 到 object 文字

[英]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 根据接收到的内容返回文字类型,以便我可以使用点符号访问属性?

You need to use a generics .您需要使用generics

Typescript rpl Typescript rpl

interface A{
  a: string,
  b: number
}

const B = <T extends Record<string, A>>(arg: T): T => arg;

const c = B({
  a: {
    a: "test",
    b: 1
  }
})

console.log(c.a.a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何缩小字符串文字/字符串枚举值的打字稿数组 - How to narrow typescript array of string literal/string enum values 为什么 Typescript 不会将对象键缩小为字符串 - Why does Typescript not narrow object keys to string typescript - 返回一个 object 键等于输入字符串文字 - typescript - return an object with key equals to an input string literal 是否可以通过 Typescript 中的映射类型将文字对象中的值(不是键)作为文字而不是其类型(例如字符串)获取? - Is it possible to get the value (not key) in a literal object as a literal, not its type (such as string) via mapped type in Typescript? 键名缩小到 TypeScript 中其他 object 的属性名称 - Key names narrow to properties names of other object in TypeScript TypeScript 不会缩小非文字类型 - TypeScript does not narrow non-literal types TypeScript中定义的对象文字键的类型是什么? - What is the type of an object literal key as defined in TypeScript? Typescript object 键映射的模板文字 - Typescript template literal for object key mapping 如何在 Angular 中制作 TypeScript 文字类型(从字符串缩小到特定字符串)? - How to make TypeScript literal types in Angular (narrow from string to specific strings)? 字符串文字Typescript中的对象实例 - Object instance from string literal Typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM