Is it possible for TypeScript to automatically determine the generic argument of assertTypeof
based on the value of expectedType
?
I am looking for a way to use the function below without having to specify number
multiple times.
type TypeLiteral = "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"
// I know its bad to return generic, but dont know how to make without it
function assertTypeof<T>(expectedType: TypeLiteral, target: any): T {
const actualType = typeof target
if (actualType === expectedType) return target
throw new Error(`Expected ${expectedType}, but got ${actualType}`)
}
const n1 = assertTypeof<number>('number', 1) // fine
const n2 = assertTypeof<number>('number', {}) // error