I have a function which looks as so:
interface Message {
id: string;
content: string;
created_at: Date;
updated_at: Date;
priority: 'low' | 'medium' | 'high'
}
function merger<T extends Message, K extends keyof T>(key: K, value: T[K], data: T) {
if (key === 'content') {
return `${data[key]}${value}`
}
return value;
}
// ...
const merge = mergeWith(merge, current, incoming);
The problem, however, is typescript is not able to infer the type correctly from the key. I would expect that if K
is content
, it would be able to infer T['content']
would be of type string
Is there a way to solve this?
Here’s what I tried. I don’t really like it
interface Message {
id: string;
content: string;
created_at: Date;
updated_at: Date;
priority: 'low' | 'medium' | 'high'
}
function isContent<T extends Message, K extends keyof T>(key: K, data: T): T[K] is string {
return key === 'content';
}
function merger<T extends Message, K extends keyof T>(key: K, value: T[K], data: T) {
if (isContent(key, value)) {
return `${data[key]}${value}`
}
return value;
}
// ...
const merge = mergeWith(merge, current, incoming);
New contributor
Alex Frazer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.