I don't understand why, in Typescript, I have this error in a varibale assignement; I think types are compatible, isn't it? To work, I have to add:
async () => {
dataFiles = <Array<DataFileLoadingInstructionType>>await Promise.all(
but why?
The error:
Type
'(DataFile | { file_path: string; header_line: number; sheets: never[]; type: string; })[]'
is not assignable to type
'({ file_path: string; } & { file_info?: string | undefined; file_name_suffix?: string | undefined; command_parameters?: string[] | undefined; } & { type: "unknown"; })[]'.
This is my the index.ts example:
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}`
);
})();
And this is my the types.ts example:
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
>;