在运行时使用Typescript验证对象的类型?

问题描述

对于我当前正在处理的项目,一个使用后端API(用Go编写)的SDK,我想实现运行时类型检查。在过去的几年中,我与Typescript进行了深入的合作,我知道在运行时不能保证类型安全,因为在编译阶段所有类型注释都将丢失。

我有一些项目将Typescript用作生产依赖项,例如生成自定义JSON解码器,以允许基于Typescript接口https://github.com/PicnicSupermarket/aegis进行代码生成

想到一个想法,就是使用Typescript作为依赖项,并使用它来检查接口,但是由于我不太熟悉Typescript编译器的结构,所以我不知道有什么可能。 / p>

所以我的问题是:是否可以将Javascript对象与Typescript接口一起使用,并验证Javascript对象是否满足Typescript接口?如果可以通过以某种方式将Typescript编译器作为生产依赖项来调用来实现。

为了提供更多的背景信息,这是我正在使用的SDK中传递结果的功能

const throwOrReturn = <T>(result: APIResult<T>): T => {
    if (result.error) {
        throw new Error(result.error);
    }
    // We can assume that data is valid (type T) if no error was found
    return result.data as T;
};

interface APIResultSuccess<T> { data: T; error?: undefined; }
interface APIResultFailure { data?: undefined; error: string; }
type APIResult<T> = APIResultSuccess<T> | APIResultFailure;

return result.data as T;之前,我想检查result.data是否有效,如果在运行时分配了类型T。因此,当前我正在使用泛型,但是要进行一层检查,使我可以访问实际接口而不是泛型,这不是问题。

如何实现throwOrReturn的示例:

interface ReturnValues {
    // Some interface code
}

const exampleCall = async (config: Config): Promise<interface> => {
    const res = await get<interface>(config,GetEndpoints.EndpointWeNeed); // Wrapper for making API calls and 4xx/5xx error handling 
    return throwOrReturn(res);
};

export default exampleCall;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)