[英]Typescript map object to array with new objects, according to fields
I have an object with some concrete fields: 我有一个带有一些具体字段的对象:
const obj1: Obj = {
hello: true,
second: false,
third: 311,
fifty: 50
.....
}
I need to map some fields from this object to concrete number, (and use it value) and return array with it: 我需要将此对象的一些字段映射到具体数字(并使用它的值)并返回数组:
interface ArrayItem {
index: number;
visible: boolean;
}
// hello should be mapped to 3, and visible - 'true'
// result is:
const arr: ArrayItem[] = [{index: 3, visible: true}]
For concrete field. 用于混凝土领域。 eg if obj1, has field "hello", result will be:
例如,如果obj1的字段为“ hello”,则结果为:
[
{
index: 3
visible: (value of 'hello', so -> true)
}
]
More examples: 更多示例:
const obj1: Obj = {
hello: true,
second: false,
third: 311,
fifty: 50
.....
}
// fields, which i looking: //字段,我在看:
const mapped = {
hello: 3, // index value
second: 5 // index value
}
output: 输出:
[
{
index: 3
visible: (value of 'hello', so -> true)
}
{
index: 5
visible: (value of 'second', so -> false)
}
]
Let's declare type definition of Obj 让我们声明Obj的类型定义
type Obj = { [key: string]: boolean };
Object with many key, and bool on all values. 具有许多键的对象,并且对所有值进行布尔化处理。
Array items look like this: 数组项如下所示:
interface ArrayItem {
index: number;
visible: boolean;
}
But we can get some more knowledge about types based on values from Obj
. 但是我们可以从
Obj
值中获得更多有关类型的知识。 To declare that let's write InterfaceParser
generic. 为了声明这一点,让我们编写
InterfaceParser
泛型。
type InterfaceParser<T extends Obj> = {
index: T['hello'] extends true ? 3 : number;
visible: boolean;
}
T extends Obj
means that input type must be at least Obj
. T extends Obj
意味着输入类型必须至少为Obj
。 extends true ? 3 : number
extends true ? 3 : number
means that when hello key is true the type of index is not number
is 3
. extends true ? 3 : number
表示当hello键为true时,索引的类型不是number
为3
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.