How to get type from its string representation

Viewed 955

How to to make typescript derive generic argument of assertTypof based on value of expectedType

Namely, I want to apply function below without specifying number two times

playable example

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
1 Answers
Related