Reputation: 497
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. e.g. if obj1, has field "hello", result will be:
[
{
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)
}
]
Upvotes: 0
Views: 764
Reputation: 2486
Let's declare type definition of 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
. To declare that let's write InterfaceParser
generic.
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
. extends true ? 3 : number
means that when hello key is true the type of index is not number
is 3
.
Upvotes: 1