[Typescript] Step6: Types at Runtime
typescript at runtime types
2023-09-14 08:59:12 时间
Step 5: Types at Runtime
This problem often happens when APi return the data.
let cachedAllTeamsList: Promise<ITeam[]>;
export async function getAllTeams(): Promise<ITeam[]> {
if (typeof cachedAllTeamsList === 'undefined')
cachedAllTeamsList = apiCall('teams');
return await cachedAllTeamsList;
}
In this line of code: apiCall('teams');
It is actually Promise<any>
, and because we set cachedAllTeamsList: Promise<ITeam[]>
, we cannot make sure whether there is any wired types going on.
Way to solve the problem is by: asserting and throw if the types we want is different.
function isITeam(arg: any): arg is ITeam {
/**
* {
iconUrl: string;
name: string;
id: string;
channels: IChannel[];
}
*/
return (
typeof arg.iconUrl === 'string' &&
typeof arg.name === 'string' &&
typeof arg.id === 'string' &&
Array.isArray(arg.channels)
);
}
function assertIsTypedArray<T>(
arg: any,
check: (val: any) => val is T,
): asserts arg is T[] {
if (!Array.isArray(arg)) {
throw new Error(`Not an array: ${JSON.stringify(arg)}`);
}
if (arg.some((item) => !check(item))) {
throw new Error(`Violators found: ${JSON.stringify(arg)}`);
}
}
let cachedAllTeamsList: Promise<ITeam[]>;
export async function getAllTeams(): Promise<ITeam[]> {
if (typeof cachedAllTeamsList === 'undefined')
cachedAllTeamsList = apiCall('teams').then((teams) => {
assertIsTypedArray(teams, isITeam);
return teams;
});
return await cachedAllTeamsList;
}
相关文章
- 用 TypeScript 实现斐波那契数列
- 如何处理TypeScript中的可选项和Undefined
- 「使用 webpack 5 从0到1搭建React + TypeScript 项目环境」3. 资源模块
- TypeScript 实用工具类型之 Pick 类型
- TypeScript 实用工具类型之 Partial 类型
- 解决 Typescript 文件被识别为视频的问题
- TypeScript,我从不喜欢到沉迷
- 类型体操:探究 TypeScript 内置高级类型
- 解释器模式举例-TypeScript 类型体操天花板,用类型运算写一个 Lisp 解释器
- TypeScript | 笔记
- 用TodoList实例告诉你怎么在项目中使用TypeScript
- 关于 2022 年 JavaScript 生态调查报告:TypeScript持续主导,Vite和Tauri大受欢迎
- Typescript学习笔记,从入门到精通,持续记录
- (十四)与 TypeScript 集成
- Webpack搭建简单的TypeScript脚手架
- Node.js脚手架开发完全指南「TypeScript版」
- 计划任务『Linux下建立AT计划任务的步骤』(linux建立at)
- TypeScript 4.4 RC 发布