zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] Step 7. Tests for Types

typescript for types step tests
2023-09-14 09:00:45 时间

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)

Dtslint docs

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)

TSD Docs

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.