我遇到了以下代码的问题。
它基本上应该做什么。它应该加载并解析给定的 JSON 文件。在 RequestListender 中,它应该显示 ID
和 Hello
字符串,它由 Product.ts 中的 ToString()
方法返回。在 tProduct.Id
正确显示的情况下,tProduct.ToString()
方法失败并出现如下错误。
非常感谢。
错误信息:
TypeError: tProduct.ToString is not a function.
(In 'tProduct.ToString()', 'tProduct.ToString' is undefined)
文件:Test.ts
var currentProduct = null as pvis.Product;
function runTest(path) {
var request = new XMLHttpRequest();
request.onload = loadRequestListener;
request.open("get", path, true);
request.send();
}
function loadRequestListener () {
var tProduct : pvis.Product = JSON.parse(this.responseText);
if (tProduct.Id) {
currentProduct = tProduct;
alert('loaded with Id: ' + tProduct.Id );
alert('loaded with Content: ' + tProduct.ToString() );
}
else {
alert('product failed to load');
}
}
文件 Product.ts
module pvis {
export class Product {
Id: string;
ToString():string {
return 'Hello';
}
}
}
HTML 部分:
<body onload="runTest('assets/products/json/A379N.json')">
编译后的 Javascript:
var pvis;
(function (pvis) {
var Product = (function () {
function Product() {
}
Product.prototype.ToString = function () {
return 'Hello';
};
return Product;
})();
pvis.Product = Product;
})(pvis || (pvis = {}));
var currentProduct = null;
function runTest(path) {
var request = new XMLHttpRequest();
request.onload = loadRequestListener;
request.open("get", path, true);
request.send();
}
function loadRequestListener() {
var tProduct = JSON.parse(this.responseText);
if (tProduct.Id) {
currentProduct = tProduct;
alert('loaded with Id: ' + tProduct.Id);
alert('loaded with Content: ' + tProduct.ToString());
}
else {
alert('product failed to load');
}
}
tsconfig.json(我不确定它是否相关):
{
"compilerOptions": {
"target": "ES5",
"removeComments": true,
"preserveConstEnums": true,
"out": "js/main.js",
"sourceMap": true
},
"files": [
"src/Test.ts"
]
}
最佳答案
行:
var tProduct : pvis.Product = JSON.parse(this.responseText);
错了。它编译的原因只是因为 JSON.parse
返回 any
。
要使用 Product
类,您必须以某种方式创建它的一个实例。 JSON 解析不会这样做,它只会返回一个包含解析后的 JSON 的对象,它不会是 pvis.Product
类的实例。
如果您想做的是键入 JSON 结果,您可以使用界面来完成。例如,如果您在表单上有一个 JSON 对象:
{
id: "some value",
name: "some name",
count: 4
}
您可以使用界面输入:
interface myInterface {
id: string;
name: string;
count: number;
}
然后像这样使用它:
var myParsedAndTypedJson: myInterface = JSON.parse("....");
像这样创建的对象永远不会有方法,但是,如果您想要该功能,您必须将此信息传递给可以以某种方式使用它的类,例如;
class myClass implements myInterface {
get id(): string { return this.initData.id; }
get name(): string { return this.initData.name; }
get count(): number { return this.initData.count; }
constructor(private initData: myInterface) {
}
public ToString() {
return this.id + ' ' + this.name + ' ' + this.count;
}
}
可以找到这方面的工作示例 here .
您可能想查看如何使用 typescript 接口(interface)和 JSON 以了解更多有关其工作原理的信息。
关于javascript - Typescript - TypeError myclass.myFunction 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34031448/