无法识别 TypeScript 类中的函数属性



我正在尝试创建一个具有类型函数的可选属性的TypeScript类。此属性具有默认实现,但构造时的新对象可以重写此函数属性的默认实现。

例如

export class MyObj {
public props: MyObjProps;
constructor({
title,
isHidden = false,
format = (val) => val,
}: MyObjProps) {
this.props = arguments[0];
}
}
interface MyObjProps {
title: string;
isHidden?: boolean;
format?: (val: string) => string;
}

然后,如果我创建一个实例

const myObj = new MyObj({
title: "Blah", 
format: (val) => "custom: " + val
});

我确实myObj.props.format("something")而不是得到custom: something它说format is not a function.

到底发生了什么?我不明白为什么它不起作用。任何帮助非常感谢!

你需要像这样调整代码

interface MyObjProps {
title: string;
format?: (val: string) => string;
}
class MyObj {
public props: MyObjProps;
constructor(x: MyObjProps) {
this.props = x;
}
}

const myObj = new MyObj({
title: "Blah", 
format: (val: string) => "custom: " + val
});
var y = myObj.props.format("123");
console.log(y);

最新更新