Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在typescript中使用外部方法/函数检查定义的变量_Typescript - Fatal编程技术网

如何在typescript中使用外部方法/函数检查定义的变量

如何在typescript中使用外部方法/函数检查定义的变量,typescript,Typescript,我有这样一个代码: function checkDefined(v: any): boolean { // external function return v !== undefined } function mult(m?: number): number { if (checkDefined(m)) return m * 3; // <<< Object is possibly 'undefined'. if (m !== u

我有这样一个代码:

function checkDefined(v: any): boolean { // external function
    return v !== undefined
}

function mult(m?: number): number {
    if (checkDefined(m)) 
        return m * 3; // <<< Object is possibly 'undefined'.

    if (m !== undefined) 
        return m * 3; // OK

    throw new Error('"m" is not defined"')    
}
函数checkDefined(v:any):布尔{//外部函数
返回v!==未定义
}
函数mult(m?:编号):编号{
如果(检查定义(m))
返回m*3;//您可以使用(执行运行时检查以保证某个范围内的类型的表达式):

函数检查已定义(v:T |未定义):v是T{
返回v!==未定义
}

function checkDefined<T>(v: T | undefined): v is T {
    return v !== undefined
}