打字稿中的类型分配

用户 1

我不明白为什么在 Typescript 中,我在变量赋值中出现此错误;我认为类型是兼容的,不是吗?为了工作,我必须添加:

async () => {
  dataFiles = <Array<DataFileLoadingInstructionType>>await Promise.all(

但为什么?错误:

类型 '(DataFile | { file_path: string; header_line: number; sheet: never[]; type: string; })[]' 不可分配给类型 '({ file_path: string; } & { file_info?: string | undefined ; file_name_suffix?: string | undefined; command_parameters?: string[] | undefined; } & { type: "unknown"; })[]'.

这是我的 index.ts 示例:

import { DataFileLoadingInstructionType } from "./types_async";
import * as path from "path";

type DataFile = {
  file_path: string;
  type: "unknown";
};

const originalDataFiles: Array<DataFile> = [];
originalDataFiles.push({ file_path: "myFile.txt", type: "unknown" });

let dataFiles: Array<DataFileLoadingInstructionType>;

async function convertPathIfLocal(dataFile: string) {
  if (dataFile.indexOf("://") === -1 && !path.isAbsolute(dataFile)) {
    dataFile = path.join("my_dir/", dataFile);
  }
  return dataFile;
}

(async () => {
//here, I have to add <Array<DataFileLoadingInstructionType>> to work
  dataFiles = await Promise.all(
    originalDataFiles
      .filter((f) => f !== undefined)
      .map(async (dataFile) => {
        if (typeof dataFile === "string") {
          return {
            file_path: await convertPathIfLocal(dataFile),
            header_line: 0,
            sheets: [],
            type: "csv",
          };
        } else {
          dataFile.file_path = await convertPathIfLocal(dataFile.file_path);
          return dataFile;
        }
      })
  );

  console.log(
    `OUTPUT: ${JSON.stringify(
      dataFiles
    )} - type of dataFiles: ${typeof dataFiles}`
  );
})();

这是我的 types.ts 示例:

import {
  Array,
  Literal,
  Number,
  Partial as RTPartial,
  Record,
  Static,
  String,
  Union,
} from "runtypes";



const UnknownDataFileLoadingInstructionTypeOptions = Record({
  type: Literal("unknown"),
});

export const DataFileLoadingInstructionType = Record({ file_path: String })
  .And(
    RTPartial({
      file_info: String,
      file_name_suffix: String,
      command_parameters: Array(String),
    })
  )
  .And(Union(UnknownDataFileLoadingInstructionTypeOptions));

export type DataFileLoadingInstructionType = Static<
  typeof DataFileLoadingInstructionType
>;
贝努瓦

从我读到的这些代码片段来看,类型实际上是不可分配的。

一方面,dataFiles用 type 声明,Array<DataFileLoadingInstructionType>换句话说:

declare const dataFiles: Array<
  | { file_path: string, file_info?: string, file_name_suffix?: string, command_parameters?: string[] }
  | { type: 'unknown' }
>

另一方面,的返回值originalDataFiles.filter(...).map(...)是:

{
  file_path: string   // await convertPathIfLocal(dataFile)
  header_line: number // 0
  sheets: never[]     // [] inferred as Array<never>
  type: string        // "csv"
}

(参见从if分支返回的对象,在 内map

或者:

DataFile

(参见从else分支返回的对象,在 内map

所以,我们最终得到:

  • dataFiles 类型:

    Array<
       | { file_path: string, file_info?: string, file_name_suffix?: string, command_parameters?: string[]}
       | { type: 'unknown' }
    >
    
  • await Promise.all(originalDataFiles.filter(...).map(...)) 类型:

    Array<
       | { file_path: string, header_line: number, sheets: never[], type: string }
       | DataFile
    >
    

事实上,它们都是不可分配的:

  • 性能header_linesheets以及type缺少的类型DataFileLoadingInstructionType
  • 该财产file_path存在于DataFile但不存在UnknownDataFileLoadingInstructionTypeOptions

我会说你应该:

  • 将 3 个属性添加到DataFileLoadingInstructionType,否则在 的if分支中调整返回的对象map以使其与 兼容DataFileLoadingInstructionType
  • file_path从 的分支中dataFile返回的属性中删除该属性,或将该属性添加到该类型。elsemapfile_pathUnknownDataFileLoadingInstructionTypeOptions

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章