实例上下文类型可以输入吗?

时间:2018-08-24 18:20:52

标签: typescript

在我提出功能请求之前,TypeScript是否可以根据作用域中调用了哪些方法来告知实例属性的类型?例如,在此代码中,仅在readAsDataURL()上调用了const fileReader,因此fileReader.result必须是字符串,但其类型仍为string | ArrayBuffer

public blobToDataURL(data: Blob): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    const fileReader: FileReader = new FileReader();
    fileReader.addEventListener('error', event => {
        reject(fileReader.error);
    });
    fileReader.addEventListener('load', event => {
        resolve(fileReader.result as string);
    });
    fileReader.readAsDataURL(data);
  });
}

如果您删除as string,您将获得

  

'string |类型的参数ArrayBuffer'不能分配给'string'类型的参数

1 个答案:

答案 0 :(得分:2)

This isn't possible. Even if this feature existed, it would likely not be syntactically retroactive - the method call probably would never apply to a previous reference to the variable.