在TypeScript中,为什么我的类型不能正确解析?

时间:2018-07-25 04:16:43

标签: typescript

我的代码如下:

class MyFile {

    fileName: string;
    checksum: string;

    constructor(fileName: string, checksum: string) {
        this.fileName = fileName;
        this.checksum = checksum;
    }
}

async function getFile() {
    return new Promise(function(resolve, reject) {
        resolve(new MyFile("test.pdf", "abcdefgh"));
    });
}

async function run() {
    const file = await getFile();
    const fileName = file.fileName;
}

我收到以下编译错误:

error TS2339: Property 'fileName' does not exist on type '{}'.

为什么无法正确检测到MyFile类型?

2 个答案:

答案 0 :(得分:1)

The issue is that you are not assigning the MyFile type to the file variable, so the static analyzer is not aware of the properties on it. One you assign the MyFile type to file you need to add the MyFile type to the Promise returned by your getFile function.

class MyFile {

    fileName: string;
    checksum: string;

    constructor(fileName: string, checksum: string) {
        this.fileName = fileName;
        this.checksum = checksum;
    }
}

async function getFile(): Promise<MyFile> {
    return new Promise<MyFile>(function(resolve, reject) {
        resolve(new MyFile("test.pdf", "abcdefgh"));
    });
}

async function run() {
    const file: MyFile = await getFile();
    const fileName: string = file.fileName;
}

答案 1 :(得分:1)

在这种情况下,无法从参数类型推断泛型(承诺解决类型)。您可以通过明确指定编译器来提示它:

return new Promise<MyFile>((resolve, reject) => {
    ...
});

其他选项正在使用Promise.resolve快捷方式:

return Promise.resolve(new MyFile("test.pdf", "abcdefgh"));