[Typescript] Step 7. Tests for Types
Step 7: Tests for Types
The assertion type code need to be tested just as the normal code.
export 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)
);
}
export 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)}`);
}
}
We will write tests for those types code:
One way to setup tests for types is running scheduled job running everyday to see whether typescript new version released would contains breaking changes.
2. Setup dtslint (optional)
1. Create a new folder under tests
folder called types-dtslint
2. Create a tslint.json
file under types-dtslint
folder
{
"extends": "dtslint/dtslint.json",
"rules": {
"semicolon": false,
"indent": [true, "tabs"],
"no-relative-import-in-test": false
}
}
3. Create a tsconfig.json
file under types-dtslint
folder
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
// If the library is an external module (uses `export`), this allows your test file to import "mylib" instead of "./index".
// If the library is global (cannot be imported via `import` or `require`), leave this out.
"baseUrl": ".",
"paths": { "mylib/*": ["../../.dist-types/*"] }
},
"include": ["."]
}
4. Under root folder, create tsconfig.types.json
file
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": ".dist-types",
"declaration": true,
"emitDeclarationOnly": true,
"noEmit": false
},
"include": ["src"]
}
5. Run tsc -P tsconfig.types.json
Command will generate definiation files.
6. Create index.d.ts
file under tests/types-dtslint
// Minimum TypeScript Version: 3.8
It telling what minimum typescript version to test against. And also the sub-sequence release versions.
Then you need to export the types file which you want to test against:
// Minimum TypeScript Version: 3.8
export * from '../../.dist-types/data/teams';
export * from '../../.dist-types/types';
7. Create another file test.ts
along with index.d.ts
import { assertIsTypedArray, isITeam, ITeam } from '.';
const team: ITeam = null; // $ExpectError: Type 'null' is not assignable to type 'ITeam'.
console.log(team);
8. Run the test:
yarn dtslint tests/types-dtslint
Results:
ERROR: 3:7 expect TypeScript@4.3 compile error:
Type 'null' is not assignable to type 'ITeam'.
As we can see, the result output is not as good as we want, we want somthing like Jest test running, can show us what's wrong, using expect
api
3. Setup tsd (recommended)
1. Create types-tsd
folder under tests
folder
2. Create index.test-d.ts
file under types-tsd
folder
import { ITeam } from '../../src/types';
import { expectAssignable, expectNotAssignable } from 'tsd';
//const team1: ITeam = null;
expectNotAssignable<ITeam>(null);
//const team2: ITeam = { channels: [], name: '', iconUrl: '', id: '' };
expectAssignable<ITeam>({
channels: [],
name: '',
iconUrl: '',
id: '',
});
3. Create index.d.ts
file
export * from '../../.dist-types/data/teams';
export * from '../../.dist-types/types';
4. Run yarn tsd tests/types-tsd
PROS: code is much understandable and readable.
CONS: we cannot test multi typescript versions.
相关文章
- Electron+Vue3.2+TypeScript+Vite开发桌面端
- typescript 多继承_说明类的继承和多态有什么作用
- typescript 接口_typeScript
- TypeScript 实用工具类型之 Partial 类型
- typeScript 全局库 文件声明
- TypeScript 深水区:3 种类型来源和 3 种模块语法
- typescript error TS2322: Type ‘Timeout‘ is not assignable to type ‘number‘.
- Vue 3 + Typescript + Vite 基于jsplumb流程设计和流程流转
- TypeScript 的装饰器有哪些?
- typescript [接口]
- Laravel + Vue 3(Vite、TypeScript)SPA 设置
- Typescript学习笔记,从入门到精通,持续记录
- 调查:React 仍然是使用最广泛的前端框架,TypeScript 是优先选项
- 使用For循环掌控Oracle数据库(for循环oracle)
- 进程探索Linux中For循环进程管理(linux中for)
- Linux下如何优雅地使用For循环(linux下for循环)
- MySQL中使用FOR循环快速编写函数(mysql函数for)