如何从字符串表示中获取类型

时间:2017-09-15 20:49:59

标签: typescript

如何根据assertTypof

的值使打字稿派生expectedType的通用参数

即,我想在不指定number两次

的情况下应用以下功能

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 个答案:

答案 0 :(得分:2)

你可以编码字符串 - &gt;在接口中键入映射​​,并使用indexed access type operator作为assertTypeof的返回类型:

interface TypeMap {
    string: string,
    number: number,
    boolean: boolean,
    symbol: Symbol,
    undefined: undefined,
    object: object,
    function: Function
};

function assertTypeof<N extends keyof TypeMap>(expectedType: N, target: any)
 : TypeMap[N] {
    const actualType = typeof target
    if (actualType === expectedType) return target

    throw new Error(`Expected ${expectedType}, but got ${actualType}`)
}

const n1 = assertTypeof('number', 1) // fine
const n2 = assertTypeof('number', {}) // runtime error