Implement interface
Trong TypeScript, class có thể implement interface. Để implement, sử dụng từ khóa implements.
tsinterfaceHuman {think (): void;}classDeveloper implementsHuman {think (): void {console .log ("Mình sẽ implement như thế nào nhỉ~");}}
tsinterfaceHuman {think (): void;}classDeveloper implementsHuman {think (): void {console .log ("Mình sẽ implement như thế nào nhỉ~");}}
Có thể chỉ định nhiều interface. Trong trường hợp đó, liệt kê các interface phân tách bằng dấu ,.
tsinterfaceHuman {think (): void;}interfaceProgrammer {writeCode (): void;}classTypeScriptProgrammer implementsHuman ,Programmer {think (): void {console .log ("Mình sẽ viết code như thế nào nhỉ~");}writeCode (): void {console .log ("Tạch tạch tạch");}}
tsinterfaceHuman {think (): void;}interfaceProgrammer {writeCode (): void;}classTypeScriptProgrammer implementsHuman ,Programmer {think (): void {console .log ("Mình sẽ viết code như thế nào nhỉ~");}writeCode (): void {console .log ("Tạch tạch tạch");}}
Để implement field được định nghĩa trong interface ở class, định nghĩa field ở phía class.
tsinterfaceHuman {name : string;}classDeveloper implementsHuman {name : string = "Bob";}
tsinterfaceHuman {name : string;}classDeveloper implementsHuman {name : string = "Bob";}