为参数指定多个类型 - 参数传递出错

时间:2017-09-07 09:47:42

标签: typescript types parameters

为什么这段代码会失败?

/**
 * Write the provided contents to a file in the specified directory.
 */
public writeFile(subPath: string, contents: string | Object) {
  // stringify the contents if they are not already
  if (contents && typeof contents === 'object') contents = JSON.stringify(contents);

  this.file.writeFile(this.path, subPath, contents);
}

出现以下错误:

Argument of type 'string | Object' is not assignable to parameter of type 'string | ArrayBuffer | Blob'. Type 'Object' is not assignable to type 'string | ArrayBuffer | Blob'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Type 'Object' is not assignable to type 'Blob'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'size' is missing in type 'Object'.

我理解writeFile(...);第三个属性Object不接受text。但是,我已经在if语句中将其字符串化了......

writeFile(...);的签名如下所示:

/** Write a new file to the desired location.
 *
 * @param {string} path Base FileSystem. Please refer to the iOS and Android filesystems above
 * @param {string} fileName path relative to base path
 * @param {string | Blob} text content or blob to write
 * @param {IWriteOptions} options replace file if set to true. See WriteOptions for more information.
 * @returns {Promise<any>} Returns a Promise that resolves to updated file entry or rejects with an error.
 */
writeFile(path: string, fileName: string, text: string | Blob | ArrayBuffer, options?: IWriteOptions): Promise<any>;

错误询问我是否打算使用any - 我没有,因为我想要更严格的控制,因为我想控制哪些可以和不能传递给这个函数。

我如何克服这个问题?

1 个答案:

答案 0 :(得分:2)

为字符串化contents使用另一个变量。

打字稿无法在编译时中知道您的内容是否会被解析为字符串或将保持为object

编译器在if声明中看不到你在做什么。它只看到contents的类型为string | object,因此可能会有一个object,当您将其传递给writeFile函数参数时,该参数仅为{{1}它抱怨你。

看看我在string上调用toString()以确保编译器我的三元运算符的两边返回contents

string