Answer the question
In order to leave comments, you need to log in
How to correctly tell the typescript about type inference in a template function?
Essence:
type Value<T> = (() => T) | T
function funcStr(value: Value<string>): string {
return typeof value === 'function' ? value() : value
}
function funcTpl<T>(value: Value<T>): T {
return typeof value === 'function' ? value() : value
}
Answer the question
In order to leave comments, you need to log in
Option 1, use a custom type guard:
type Value<T> = (() => T) | T
function isFunctionValue<T>(value: Value<T>): value is () => T {
return typeof value === 'function'
}
function funcStr(value: Value<string>): string {
return isFunctionValue(value) ? value() : value
}
function funcTpl<T>(value: Value<T>): T {
return isFunctionValue(value) ? value() : value
}
type Value<T> = T extends (...args: never[]) => unknown ? never : (() => T) | T
function funcStr(value: Value<string>): string {
return typeof value === 'function' ? value() : value
}
function funcTpl<T>(value: Value<T>): T {
return typeof value === 'function' ? value() : value
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question