示例工程 03-literal-types-narrowing

03-literal-types-narrowing/05-assertion-functions/types.test-d.ts

typescript · 0.6 KB

运行:03 · assertion-functions

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

type Equal<A, B> =
  (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
 
import { assertDefined, assertIsString } from './src/main.js';
 
type Case1 = Expect<Equal<ReturnType<typeof assertIsString>, void>>;
type Case2 = Expect<Equal<ReturnType<typeof assertDefined<string | undefined>>, void>>;
 
// 断言之后的收窄是编译期证据:这行能通过就说明 value 被当成 string
function useAfterAssert(value: unknown): string {
  assertIsString(value, 'value');
  const narrowed: string = value;
  return narrowed;
}
 
export { useAfterAssert };