Estoy tratando de convertir muchos archivos JS con signos de interrogación dobles a TypeScript usando tsc.
Pero desafortunadamente el compilador tsc no entiende ??. Ejemplo: this.x = typeof params.x == "string" ? this._processStringParam(params.x, "x") : params.x ?? 0;
Simplemente arroja un error: imageElement.js:70:96 - error TS1109: Expresión esperada. this.x = typeof params.x == "cadena" ? this._processStringParam(params.x, "x") : params.x ?? 0;
No entiendo una cosa. Este doble signo de interrogación es la principal razón para convertirse a TS. ¿Qué sentido tiene para mí arreglarlo en JS antes de tsc entonces?
¿Cómo convertir tales archivos js a TypeScript entonces?
tsconfig.json se ve así:
{ "compilerOptions": { "checkJs": false, "module": "commonjs", "target": "ES5", "allowJs": true, "rootDir": "./", "baseUrl": "./", "outDir": "./build", "noStrictGenericChecks": true, "skipLibCheck": true, "strictFunctionTypes": false, "lib": [ "es2015", "dom" ] }, "exclude": [ "./build/**" ] }Pruébelo cambiando el objetivo a "ES6"
Esto se debe a que el ?? o se agrega una operación de fusión nula después de ES2020
Prueba esta configuración:
"compilerOptions": { /* Language and Environment */ "target": "ES5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ /* Modules */ "module": "commonjs", /* Specify what module code is generated. */ "outDir": "dist", /* Specify an output folder for all emitted files. */ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ /* Type Checking */ "strict": true, /* Enable all strict type-checking options. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */ }código ts:
console.log('coallescing nullish with undefined: ', undefined ?? 'compare with undefined'); console.log('coallescing nullish with null: ', null ?? 'compare with null'); console.log('coallescing nullish with valid data: ', 'with data' ?? 'compare with null or undefined');código transpilado a js:
console.log('coallescing nullish with undefined: ', undefined !== null && undefined !== void 0 ? undefined : 'compare with undefined'); console.log('coallescing nullish with null: ', null !== null && null !== void 0 ? null : 'compare with null'); console.log('coallescing nullish with valid data: ', 'with data' !== null && 'with data' !== void 0 ? 'with data' : 'compare with null or undefined');Resultados en consola:
coallescing nullish with undefined: compare with undefined coallescing nullish with null: compare with null coallescing nullish with valid data: with dataEste código js tiene compatibilidad con ES5.