การแคสติ้ง - ฉันจะใช้วิธีใดในการใช้อินเทอร์เฟซที่สามารถเรียกใช้งานได้และมีคุณสมบัติใน TypeScript?
เมื่อพิจารณาจากอินเทอร์เฟซ
interface FooWithBar {
():void;
bar():void;
}
ฉันจะเขียนการนำไปใช้ได้อย่างไร?
function foo(){
}
foo.bar = function(){
};
ไม่สามารถทำงานได้ เนื่องจากเกิดข้อผิดพลาด, "Property 'bar' does not exist on type '() => void'" แต่ถ้าฉันประกาศชนิดของ foo ให้เป็น FooWithBar
``` var foo: FooWithBar=function() {
};
foo.bar = function () {
};
````
ฉันได้รับข้อผิดพลาดอีกครั้ง, "ประเภท '() => void' ไม่สามารถกำหนดค่าให้กับประเภท 'FooWithBar' ได้. ไม่มีคุณสมบัติ 'bar' ในประเภท '() => void'".
ฉันจะแก้ปัญหาที่เป็นกับดักแบบนี้ได้อย่างไร?
คำตอบ #1
function FooWithBar() {
// ...
}
module FooWithBar { // n.b. can use 'namespace' keyword here instead of 'module' if you like
export function bar() {
// ...
}
}
นี่คือข้อความบางส่วนเพื่อหลีกเลี่ยงไม่ให้ตกไปอยู่ในคิวตรวจสอบ 'คำตอบแบบโค้ดอย่างเดียว'
คำตอบ #2
มีหลายวิธีในการแก้ปัญหานี้:
สมมติว่าระบบอินเทอร์เฟซเป็นดังนี้:
interface FooWithBar
{
():void;
bar():void;
}
การส่งออกเนมสเปซ
function FooWithBar(){
}
namespace FooWithBar{
export function bar(){
}
}
การคัดเลือกนักแสดง
let foo:FooWithBar = function(){
} as FooWithBar;
foo.bar = function(){
};
คำสำคัญ namespace ไม่สามารถใช้ในตัวฟังก์ชันได้ ดังนั้นถ้าคุณต้องการตัวสร้าง foo ให้ใช้วิธีที่สอง
