zoukankan      html  css  js  c++  java
  • xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

    TypeScript 3.7 RC & Assertion Functions

    assertion functions, assert

    https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-rc/#assertion-functions

    function yell(str) {
        assert(typeof str === "string");
    
        return str.toUppercase();
        //         ~~~~~~~~~~~
        // error: Property 'toUppercase' does not exist on type 'string'.
        //        Did you mean 'toUpperCase'?
    }
    
    function assert(condition: any, msg?: string): asserts condition {
        if (!condition) {
            throw new AssertionError(msg)
        }
    }
    
    
    
    function assertIsString(val: any): asserts val is string {
        if (typeof val !== "string") {
            throw new AssertionError("Not a string!");
        }
    }
    
    // Here asserts val is string ensures that after any call to assertIsString, any variable passed in will be known to be a string.
    
    function yell(str: any) {
        assertIsString(str);
    
        // Now TypeScript knows that 'str' is a 'string'.
    
        return str.toUppercase();
        //         ~~~~~~~~~~~
        // error: Property 'toUppercase' does not exist on type 'string'.
        //        Did you mean 'toUpperCase'?
    }
    
    

    type predicate signatures

    
    function isString(val: any): val is string {
        return typeof val === "string";
    }
    
    function yell(str: any) {
        if (isString(str)) {
            return str.toUppercase();
        }
        throw "Oops!";
    }
    
    

    assertion signatures

    
    function assertIsDefined<T>(val: T): asserts val is NonNullable<T> {
        if (val === undefined || val === null) {
            throw new AssertionError(
                `Expected 'val' to be defined, but received ${val}`
            );
        }
    }
    
    
    

    refs

    https://www.cnblogs.com/xgqfrms/tag/TypeScript 3.7 RC/



    ©xgqfrms 2012-2020

    www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


  • 相关阅读:
    POJ题目分类
    最短路&记录记录记录路径
    博弈论
    生成树模板总结
    弱鸡的暑假图论安排
    面试随缘做题--day2
    面试随缘做题---day1
    PAT第四章速刷
    PAT第二章知识点快速复习
    sql语句快速复习
  • 原文地址:https://www.cnblogs.com/xgqfrms/p/11749488.html
Copyright © 2011-2022 走看看