#user define type guard question

2 messages · Page 1 of 1 (latest)

desert marsh
#

In the below code the function isString will work even if we don't mention that test is string. What then this fancy sytax is doing here can anyone explain? I want to what is real purpose of it..

function isString(test: any): test is string {
    return typeof test === "string";
}

let value: any = "true";

if (isString(value)) {
    console.log(value.length); // Now TypeScript knows `value` is a string
} else {
    console.log("Is not a String"); // Now TypeScript knows `value` is a boolean
}
candid pecan
#

If you remove test is string it does not work properly, it "works" improperly because you are using any which literally allows you to do anything.