简体   繁体   English

Typescript object 类型定义的属性

[英]Typescript object property from type definiton

I'll describe the problem as simply as possible我会尽可能简单地描述问题

I have a type composed of forced strings eg:我有一个由强制字符串组成的类型,例如:

type myType = 'name' | 'age' | 'family' | 'other';

I'm going to create a type that forces me to write this我要创建一个强制我写这个的类型

const myObject: myCastType<myType> = {
    name: 'string',
    age: 'string',
    family: 'string',
    other: 'string',
}

so what I would like to create myCastType所以我想创建myCastType

what I'm missing is the step that allows me to force an object to be composed of properties called by the passed types我缺少的是允许我强制 object 由传递的类型调用的属性组成的步骤

to make you understand better I'm not interested in being able to create a type eg:为了让您更好地理解,我对创建类型不感兴趣,例如:

type Person = { name: string, age: string, family: string, other: string }

const myObject: Person = { ... }

My problem is that props like 'name', 'age', etc... don't know them and they change in the various implementation i want to do so i need to define them dynamically我的问题是像“姓名”、“年龄”等道具......不知道它们并且它们在我想做的各种实现中发生变化所以我需要动态定义它们

I tried to search for something about it but no one mentions my problem or anything similar, but unfortunately I haven't found anything that can help me.我试图搜索有关它的内容,但没有人提到我的问题或类似问题,但不幸的是,我没有找到任何可以帮助我的东西。

of course I tried things like Pick, Record, Extract, etc, basically a good part of those present on 'lis.es5.d.ts'当然,我尝试了 Pick、Record、Extract 等,基本上是 'lis.es5.d.ts' 上的大部分内容

Does anyone have any ideas or can direct me to a more correct path.有没有人有任何想法或可以指导我走更正确的道路。 links, documentation or any material is welcome欢迎使用链接、文档或任何材料

You'll be glad to know that the "cast type" already exists — Record :你会很高兴知道“演员类型”已经存在—— Record

type MyType = "name" | "age" | "family" | "other";

const myObject: Record<MyType, string> = {
    name: "string",
    age: "string",
    family: "string",
    other: "string",
};

Record<MyType, string> means "a record (object) with the property names from MyType [which can aa simple type or a union] and the values string ." Record<MyType, string>表示“一个记录(对象),其属性名称来自MyType [可以是简单类型或联合],值是string 。”

If you left out any of those properties, TypeScript would complain the object wasn't valid.如果您遗漏了任何这些属性,TypeScript 会抱怨 object 无效。

Playground example 游乐场示例

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM