Is there a way to create an object using keys from another object and determine the type based on a string? For example:
const result = rebuild(query, {
name: 'string'
});
// query - { name: '123', dont_need: true }
// result - { name: '123' }
I have written the function, but I am having difficulty with typing. I attempted the following approach:
type Type = 'string' | 'number';
type Config = Record<string, Type>;
interface ConfigType {
string: string;
number: number;
}
type RebuiltResult<T extends Config> = {
[key in keyof T]: ConfigType[T[keyof T]]
}
However, the return type shows that name
could be either a string
or number
, which makes sense because I used a general keyof T
to determine the type. I know it's possible to specify the type more precisely, but I am unsure how to do so.
Here are some additional examples:
const query = {
name: 'Ivan',
money: 3000,
age: 20
}
const ivan = rebuild(query, {
name: 'string',
money: 'number'
})
// type - { name?: string; money?: number }
// value - { name: 'Ivan', money: 3000 }
const ivan = rebuild(query, {
name: 'string',
money: 'string'
})
// type - { name?: string; money?: string }
// value - { name: 'Ivan' }
// no money, since it's a number