typescript - ฉันสามารถทำการแปลงประเภทของตัวแปรในบล็อกขอบเขตได้หรือไม่?
ฉันมีโค้ดนี้:
function foo(input: Blob): void;
function foo(input: string): void;
function foo(input: any) {
if (typeof input === "string") {
}
else if (input instanceof Blob) {
}
}
ที่นี่ ฉันต้องการแปลงชนิด input ในขอบเขตบล็อกแทนที่จะกำหนดค่าใหม่ให้ตัวแปรอื่น
if (typeof input === "string") {
declare input: string;
}
else if (input instanceof Blob) {
declare input: Blob;
}
มากกว่า:
if (typeof input === "string") {
var str: string = input;
}
else if (input instanceof Blob) {
var blob: Blob = input;
}
นี่เป็นไปได้ใน TypeScript หรือไม่?
คำตอบ #1
ฉันคิดว่ารุ่นล่าสุดของ TypeScript จะทำสิ่งนี้โดยอัตโนมัติ แต่คุณต้องใช้คำสั่ง if ร่วมกับ typeof, instanceof หรือฟังก์ชันพิเศษ
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
}
ดู: https://www.typescriptlang.org/docs/handbook/advanced-types.html
คำตอบ #2
ไม่ มันเป็นไปไม่ได้ คุณต้องใช้ชื่อตัวแปรใหม่ที่มีประเภทต่างกัน
