如何根据assertTypof
expectedType
的通用参数
即,我想在不指定number
两次
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
答案 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