zoukankan      html  css  js  c++  java
  • [Typescript] Narrow the unknown Type with TypeScript's Assertion Functions

    This lesson introduces assertion functions which let us narrow the type of a variable or property for the remainder of the containing scope. We're going to learn how to create an assertion function by using the asserts keyword in the function signature. In particular, we're going to focus on narrowing the unknown type to a more specific type.

    'assert' will throw if the condition is not match.

    function assert(condition: unknown, name?: string): asserts condition {
    // Recommended using falsy condition
    if (!condition) { throw TypeError(`${name} is not a number`) } } function assertIsNumber(value: unknown, name?: string): asserts value is number{ if (typeof value !== "number") { throw TypeError(`${name} is not a number`) } } function add(x: unknown, y: unknown): number { assert(typeof x === "number", "x"); assert(typeof y === "number", "y"); return x + y; } function multiply(x: unknown, y: unknown) { assertIsNumber(x,"x"); assertIsNumber(y, "y"); return x * y; } multiply(10, 5);
  • 相关阅读:
    企业级 SpringBoot 教程 (九)springboot整合Redis
    03 网格系统
    02 表单
    01 排版
    客户端调用webSerices
    sql 一行转多行
    sql 多行转一行
    时间差计算 Stopwatch
    sql 游标
    Linq连接查询
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14725134.html
Copyright © 2011-2022 走看看