Javascript 我可以用打字稿把这个范围缩小吗?

Javascript 我可以用打字稿把这个范围缩小吗?,javascript,typescript,narrowing,type-narrowing,Javascript,Typescript,Narrowing,Type Narrowing,我有一个实用函数来检查变量是否为null或未定义,如果通过检查,我希望TypeScript缩小输入变量的范围,例如: public init(input?: string): void { function isSpecified(input: any): boolean { return (typeof input !== "undefined") && (input !== null); } if (isSpecified(input

我有一个实用函数来检查变量是否为null或未定义,如果通过检查,我希望TypeScript缩小输入变量的范围,例如:

public init(input?: string): void {
    function isSpecified(input: any): boolean {
        return (typeof input !== "undefined") && (input !== null);
    }

    if (isSpecified(input)) {
        let copiedString: string = input; // <-- Error; input is still 'string | undefined'
    }
}
public init(输入?:字符串):void{
函数已指定(输入:任意):布尔值{
返回(输入类型!==“未定义”)&&(输入!==null);
}
如果(已指定(输入)){

让copiedString:string=input;//是的,您基本上只编写了一个typeguard函数,没有添加typeguard

更改:

function isSpecified(input: any): boolean
致:

更一般地说,您可以使用同一事物的通用版本:

函数已指定(输入:null |未定义| T):输入为T

您可以使用通用类型保护功能:

public init(input?: string): void {
    function isSpecified<T>(input: null | undefined | T): input is T {
        return (typeof input !== "undefined") && (input !== null);
    }

    if (isSpecified(input)) {
        let copiedString: string = input; // OK
    }
}
public init(输入?:字符串):void{
函数已指定(输入:null |未定义| T):输入为T{
返回(输入类型!==“未定义”)&&(输入!==null);
}
如果(已指定(输入)){
让copiedString:string=input;//确定
}
}

虽然在其他答案中建议的类型保护功能在许多情况下都能很好地工作,但在这种情况下,您有另一个更简单的选择。与其检查
(输入类型!==“未定义”)&&(输入!==null)
只需内联检查
输入!=null

很容易忘记,有时由双相等
=
!=
完成的类型转换实际上是有用的:

function init(input?: string): void {
    if (input != null) {
        let copiedString: string = input; // <-- input is now 'string'
    }
}

但我不想说
是string
,它比string更通用,我想说“它不是未定义的或空的”。
public init(input?: string): void {
    function isSpecified<T>(input: null | undefined | T): input is T {
        return (typeof input !== "undefined") && (input !== null);
    }

    if (isSpecified(input)) {
        let copiedString: string = input; // OK
    }
}
function init(input?: string): void {
    if (input != null) {
        let copiedString: string = input; // <-- input is now 'string'
    }
}
undefined == null
null == null
'' != null