I have this code:
function foo(input: Blob): void;
function foo(input: string): void;
function foo(input: any) {
if (typeof input === "string") {
}
else if (input instanceof Blob) {
}
}
Here, I want to type-cast input
in block scope rather than reassign it to another variable.
if (typeof input === "string") {
declare input: string;
}
else if (input instanceof Blob) {
declare input: Blob;
}
rather than:
if (typeof input === "string") {
var str: string = input;
}
else if (input instanceof Blob) {
var blob: Blob = input;
}
Is this possible in TypeScript?
The var keyword behaves differently in function scopes and block scopes. A variable declared with var in a function scope can’t be accessed outside that function scope. A variable declared with var in a block scope is available outside of that block scope.
Block-scoped variables and functions are defined inside a particular block or inside curly { } braces and they can only be accessible inside that particular block or within that block. The block-scoped variables were first introduced in EcmaScript2015 or es6.
What are Block Scoped variables and functions in ES6 ? Block-scoped variables and functions are defined inside a particular block or inside curly { } braces and they can only be accessible inside that particular block or within that block. The block-scoped variables were first introduced in EcmaScript2015 or es6.
A variable declared with var in a function scope can’t be accessed outside that function scope. A variable declared with var in a block scope is available outside of that block scope. The i variable that we often use in a for loop will continue to exist beyond the scope of that loop, and that does not make sense, really.
I think the latest version of TypeScript does this automatically. But you have to use an if statement together with typeof
, instanceof
or a special function.
function foo(input: string|blob|whatever) {
if(typeof input === 'string') {
// input is now a string
input.blobfunction(); // Error: blobfunction() is not a method of string
} else if(input instanceof blob) {
// input is now a blob
} else if(isWhatever(input)) {
// input is now a whatever
}
}
// Probably a good idea to make this a static 'whatever.isInstance()'
function isWhatever(input: string|blob|whatever): input is whatever {
return true; // put your test for whatever here
}
See: https://www.typescriptlang.org/docs/handbook/advanced-types.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With