gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:40 25 4
gpt4 key购买 nike

如何使 typescript 根据 expectedType 的值派生 assertTypof 的泛型参数

也就是说,我想在不指定 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

最佳答案

您可以在接口(interface)中编码字符串 -> 类型映射,并使用 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

关于typescript - 如何从其字符串表示中获取类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46247277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com