Wal*_*dan 11 methods interface typescript
如何在 TypeScript 中实现接口中的方法?
interface Bar
{
num: number;
str: string;
fun?(): void;
}
class Bar
{
fun?()
{
console.log(this.num, this.str);
}
}
let foo: Bar = {num: 2, str: "B"};
foo.fun();
Run Code Online (Sandbox Code Playgroud)
预期的:2 B
实际的:
Error Cannot invoke an object which is possibly 'undefined'.ts(2722)
Run Code Online (Sandbox Code Playgroud)
如果方法中省略了可选标志fun()
,则错误将是:
Property 'fun' is missing in type '{ num: number; str: string; }' but required in type 'Bar'.ts(2741)
Run Code Online (Sandbox Code Playgroud)
这是一种解决方法,可以达到预期的效果,尽管它似乎不是执行此操作的正确方法。
if(foo.fun)
{
foo.fun();
}
Run Code Online (Sandbox Code Playgroud)
小智 15
在您正在创建的类中实现接口,然后调用。
interface BarInterface
{
num: number;
str: string;
fun: () => void;
}
class Bar implements BarInterface {
num: number;
str: string;
constructor(num: number, str: string) {
this.num = num;
this.str = str;
}
fun() {
console.log(this.num, this.str);
}
}
let foo = new Bar(2, "B");
foo.fun();
Run Code Online (Sandbox Code Playgroud)
Typescript 告诉您它是未定义的,因为您没有提供在此行中调用的方法:
let foo: Bar = {num: 2, str: "B"};
Run Code Online (Sandbox Code Playgroud)
尝试
const myTestFun = () => {
console.log('I am here!')
}
let foo: Bar = {num: 2, str: "B", fun: myTestFun };
Run Code Online (Sandbox Code Playgroud)