在我提出功能请求之前,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'类型的参数
答案 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.