- Table of contents
- An expression of type ‘void’ cannot be tested for truthiness
- An expression of type ‘void’ cannot be tested for truthiness
- Swagger-api
/
swagger-codegen
Public - Microsoft
/
TypeScript
Public - An expression of type ‘void’ cannot be tested for truthiness
Find the data you need here
We provide programming data of 20 most popular languages, hope to help you!
Previous PostNext Post
An expression of type ‘void’ cannot be tested for truthiness
localStorage.setItem('todoitems', JSON.stringify(this.todoitems))
? localStorage.setItem('todoitems', JSON.stringify(this.todoitems))
: [];
if (this.todoitems !== null)
localStorage.setItem('todoitems', JSON.stringify(this.todoitems))
An expression of type ‘void’ cannot be tested for truthiness
Copied!// 👇️ function returns type void
function sum(a: number, b: number) {
const result = a + b;
// 👉️ forgot to return
}
// ⛔️ Error: An expression of type 'void' cannot be tested for truthiness.ts(1345)
const result = sum(10, 10) ? 20 : 0;
// ⛔️ Error: An expression of type 'void' cannot be tested for truthiness.ts(1345)
if (sum(10, 10)) {
console.log('success');
}
Copied!// 👇️ function now returns a value
function sum(a: number, b: number): number {
const result = a + b;
return result; // 👈️ explicit return
}
const result = sum(10, 10) ? 20 : 0;
if (sum(10, 10)) {
console.log('success');
}
Copied!// 👇️ implicit return with objects
const getObj = () => ({
name: 'Tom',
country: 'Chile',
});
// 👇️ implicit return with primitives
const getNum = (a: number, b: number) => a + b;
Swagger-api
/
swagger-codegen
Public
…}-petstore.sh
…}-petstore.sh
…}-petstore.sh
based on swagger-api#9012
An expression of type ‘void’ cannot be tested for truthiness
localStorage.setItem('todoitems', JSON.stringify(this.todoitems))
? localStorage.setItem('todoitems', JSON.stringify(this.todoitems))
: [];
if(this.todoitems !== null)
localStorage.setItem('todoitems', JSON.stringify(this.todoitems))
Microsoft
/
TypeScript
Public
const logger = (...args) => console.log(args) || args;
const logger = (...args) => console.log(args) || args;
const logger = (...args) => (console.log(args), args);
An expression of type ‘void’ cannot be tested for truthiness
localStorage.setItem('todoitems', JSON.stringify(this.todoitems))
? localStorage.setItem('todoitems', JSON.stringify(this.todoitems))
: [];
public getUser(userId: string) {
return this.http.get<{
_id: string;
registrationStep: number;
userType: string;
isAdmin: boolean;
}>(BACKEND_URL+"getUserData/" + userId);
getIsAdmin() {
this.getUser(this.getUserId()).subscribe(result => {
return result.isAdmin;
});
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
Router
} from "@angular/router";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { AuthService } from "./auth.service";
@Injectable()
export class AdminGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean | Observable<boolean> | Promise<boolean> {
const isAdmin = this.authService.getIsAdmin();
if (!isAdmin) {
this.router.navigate(['auth/admin']);
}
return isAdmin;
}
}
// authService
getIsAdmin(): Observable<boolean> {
return this.getUser(this.getUserId()).pipe(
map(user => user.isAdmin)
);
}
canActivate(…): Observable<boolean> {
const isAdmin$ = this.authService.getIsAdmin();
return isAdmin$.pipe(
tap(isAdmin => {
if(!isAdmin) {
this.router.navigate(['auth/admin']);
}
})
);
}
Swagger-api
/
swagger-codegen
Public
parameters:
- name: attachment1
type: file
in: formData
required: false
if (attachment1 !== undefined) {
formParams = formParams.append('attachment1', <any>attachment1) || formParams;
}
let formParams: { append(param: string, value: any): void; };
import { Observable } from 'rxjs/Observable'
import { Observable } from 'rxjs'
sed -i 's/rxjs/Observable/rxjs/' ./src/app/swagger/api/api.service.ts
sed -i 's/formParams = formParams/formParams/' ./src/app/swagger/api/api.service.ts
sed -i 's/ || formParams//' ./src/app/swagger/api/api.service.ts
docker run --rm -v ${PWD}/src/app/swagger:/local swaggerapi/swagger-codegen-cli:unstable generate -i http://192.168.1.47:5070/swagger/v1/swagger.json -l typescript-angular -o /local --additional-properties ngVersion=6.0.0
let formParams: { append(param: string, value: any): void; };
let useForm = false;
let convertFormParamsToString = false;
if (useForm) {
formParams = new FormData();
} else {
formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()});
}
if (name !== undefined) {
formParams = formParams.append('name', <any>name) || formParams;
}
if (status !== undefined) {
formParams = formParams.append('status', <any>status) || formParams;
}
let formParams: { append(param: string, value: any): void; };
let formParams: { append(param: string, value: any): void | HttpParams; };
…t be tested for truthiness swagger-api#8836
…t be tested for truthiness swagger-api#8836
…t be tested for truthiness swagger-api#8836
find ./src/swagger/api/*.service.ts -type f -exec sed -i '' -e 's/rxjs//rxjs/' {} ;
find ./src/swagger/api/*.service.ts -type f -exec sed -i '' -e 's/formParams = formParams/formParams/' {} ;
find ./src/swagger/api/*.service.ts -type f -exec sed -i '' -e 's/ || formParams//' {} ;
# builder.ts, new file
export interface FormBuilder {
append(param: string, value: any): FormBuilder;
}
export class FormDataBuilder<T extends { append(param: string, value: any): void; }> implements FormBuilder {
append(param: string, value: any): FormDataBuilder<T> {
this.append(param, value);
return this;
}
}
# generated service
let formParams: FormBuilder;
if (useForm) {
formParams = new FormDataBuilder<FormData>();
} else {
formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()});
}
// HERE: if we use HttpParams the append function returns a new HttpParams object
// instead if we use FormData the append function will not return anything
let formParams: { append(param: string, value: any): void | HttpParams; };
let useForm = false;
let convertFormParamsToString = false;
if (useForm) {
formParams = new FormData();
} else {
formParams = new HttpParams({ encoder: new CustomHttpUrlEncodingCodec() });
}
if (newPassword !== undefined) {
// here there is no more the syntax error
formParams = formParams.append('newPassword', <any>newPassword) || formParams;
}
// here nothing changes
return this.httpClient.post<any>(`${this.basePath}/accounts/reset-password`,
convertFormParamsToString ? formParams.toString() : formParams,
{
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
java -jar .swagger-codegen-cli-2.4.1.jar generate -i http://localhost:5100/swagger/v1/swagger.json -l typescript-angular -o ../src/api
$file = '..srcapiapithexyz.service.ts'
$find = 'let formParams: { append(param: string, value: any): void; };'
$replace = 'let formParams: { append(param: string, value: any): void | HttpParams; };'
(Get-Content $file).replace($find, $replace) | Set-Content $file
var gen = 'java -jar src/swagger/swagger-codegen-cli-2.4.13.jar generate -i src/swagger/swagger-spec.yml -l typescript-angular -o src/app/generated';
var rxFix = 'sed -i 's/rxjs\/Observable/rxjs/' ./src/app/generated/api/*.service.ts';
var frmFix = 'sed -i "s/ || formParams//" ./src/app/generated/api/*.service.ts';
var frmFix2 = 'sed -i 's/formParams = formParams/formParams/' ./src/app/generated/api/*.service.ts';
runCommand(gen, (error, stdout, stderr) => {
console.log('Output: ' + stdout)
if(error !== null){
console.log("Error: " + error);
return;
}
if(stderr !== null){
console.log("Stderr: " + stderr);
}
});
runCommand(rxFix, (error, stdout, stderr) => {
console.log('Output: ' + stdout)
if(error !== null){
console.log("Error: " + error);
return;
}
if(stderr !== null){
console.log("Stderr: " + stderr);
}
});
runCommand(frmFix, (error, stdout, stderr) => {
console.log('Output: ' + stdout)
if(error !== null){
console.log("Error: " + error);
return;
}
if(stderr !== null){
console.log("Stderr: " + stderr);
}
});
runCommand(frmFix2, (error, stdout, stderr) => {
console.log('Output: ' + stdout)
if(error !== null){
console.log("Error: " + error);
return;
}
if(stderr !== null){
console.log("Stderr: " + stderr);
}
});
Previous PostNext Post
Same problem in our environment, after updating angular from v6 to v7 it is not possible to compile the genereated swagger services with the same error as seen above.
tried swagger-codegen-cli 2.4.0-SNAPSHOT and 3.0.2
Also happens with
import { Observable } from 'rxjs/Observable'
Which has to be :
import { Observable } from 'rxjs'
As a workaround you can use some bash after generating the code
sed -i 's/rxjs/Observable/rxjs/' ./src/app/swagger/api/api.service.ts
sed -i 's/formParams = formParams/formParams/' ./src/app/swagger/api/api.service.ts
sed -i 's/ || formParams//' ./src/app/swagger/api/api.service.ts
@Dviejopomata yeah this has been the case after updating the rxjs version to 6.0.0
@Dviejopomata , this actually has been implemented, you just need to pass the ngversion parameter while generating. The online generator is generating for angular 4.3 as a default.
@Dviejopomata , this actually has been implemented, you just need to pass the ngversion parameter while generating. The online generator is generating for angular 4.3 as a default.
do you have any pointers to what to set it? i tried with --additional-properties ngVersion=6.0.0
but that didn’t seem to do anything.
@awalland Make sure you are using v3.0.0 at least, i had to change from v2.3.1 to v3.0.0 and it worked fine:
Since i’m using docker this is what my command looks like:
docker run --rm -v ${PWD}/src/app/swagger:/local swaggerapi/swagger-codegen-cli:unstable generate -i http://192.168.1.47:5070/swagger/v1/swagger.json -l typescript-angular -o /local --additional-properties ngVersion=6.0.0
I’m facing same problem, after I updating angular from v5 to v7. I used all version of swagger cli jars. I used following command to generate swagger code
java -jar ./swagger-codegen-cli-3.0.0-20180710.190537-87.jar generate -i http:///swagger/v1/swagger.json -l typescript-angular -o ./local —additional-properties ngVersion=7.0.0
With swagger-codegen-cli-3.0.3.jar I get invalid petApi.service.ts
petApi.service.ts(364,1): error TS1005: '}' expected.
Used command is
java -jar ./swagger-codegen-cli-3.0.3.jar generate -i petstore.yaml -l typescript-angular -o ./local --additional-prop erties ngVersion=7.0.0
Same if I use ngVersion 7.1.0
Also all codegen-cli (jars) are generating invalid typescript 3 code. Errors are related to rxjs Imports and An expression of type 'void' cannot be tested for truthiness
Problematic code is
let formParams: { append(param: string, value: any): void; };
let useForm = false;
let convertFormParamsToString = false;
if (useForm) {
formParams = new FormData();
} else {
formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()});
}
if (name !== undefined) {
formParams = formParams.append('name', <any>name) || formParams;
}
if (status !== undefined) {
formParams = formParams.append('status', <any>status) || formParams;
}
useForm boolean is basically hardcoded and FormData constructor is never used.
formParams should be of this type and formParams=new FormData() line removed (i thinlk):
let formParams: { append(param: string, value: any): HttpParams; };
Proposed fix: change the line
let formParams: { append(param: string, value: any): void; };
to
let formParams: { append(param: string, value: any): void | HttpParams; };
in the template file api.service.mustache
Is there any update on this issue (or the proposed PRs)?
@plathub This fix does not work because it is not only a typing issue, formParams.append
could really return nothing or a new HttpParams with appended value.
I have resorted to running my own sanitise-swagger.sh
after each generation
find ./src/swagger/api/*.service.ts -type f -exec sed -i '' -e 's/rxjs//rxjs/' {} ;
find ./src/swagger/api/*.service.ts -type f -exec sed -i '' -e 's/formParams = formParams/formParams/' {} ;
find ./src/swagger/api/*.service.ts -type f -exec sed -i '' -e 's/ || formParams//' {} ;
This does the corrections on all files under /src/swagger which is where i keep my generated client.
@emmanuelgautier Can we not have a builder wraps around FormData that supports the same append signature ? Something similar to the below.
# builder.ts, new file
export interface FormBuilder {
append(param: string, value: any): FormBuilder;
}
export class FormDataBuilder<T extends { append(param: string, value: any): void; }> implements FormBuilder {
append(param: string, value: any): FormDataBuilder<T> {
this.append(param, value);
return this;
}
}
# generated service
let formParams: FormBuilder;
if (useForm) {
formParams = new FormDataBuilder<FormData>();
} else {
formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()});
}
@emmanuelgautier #9012 seems to be failing on angular v4, is there anything I can do to get it merged ?
I haven’t found a valid workaround amongst the comments above… This problem appears also with _openapi-generator_ every time an endpoint function has to use FormData or HttpParam. My solution was to define differently the formData variable so it can return void or something like a new HttpParam:
// HERE: if we use HttpParams the append function returns a new HttpParams object
// instead if we use FormData the append function will not return anything
let formParams: { append(param: string, value: any): void | HttpParams; };
let useForm = false;
let convertFormParamsToString = false;
if (useForm) {
formParams = new FormData();
} else {
formParams = new HttpParams({ encoder: new CustomHttpUrlEncodingCodec() });
}
if (newPassword !== undefined) {
// here there is no more the syntax error
formParams = formParams.append('newPassword', <any>newPassword) || formParams;
}
// here nothing changes
return this.httpClient.post<any>(`${this.basePath}/accounts/reset-password`,
convertFormParamsToString ? formParams.toString() : formParams,
{
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
By using this everytime we use FormData/HttpParams the HTTP requests result valid.
Still valid for v3.0.11. Is this gonna be resolved any soon?
hi @Hobart2967 , just assign it to myself, sadly i cant guarantee solve it soon, but once i have a chance i’ll work on it
Just like @itsTeknas I have used a script (powershell) to solve this for the time being
java -jar .swagger-codegen-cli-2.4.1.jar generate -i http://localhost:5100/swagger/v1/swagger.json -l typescript-angular -o ../src/api
$file = '..srcapiapithexyz.service.ts'
$find = 'let formParams: { append(param: string, value: any): void; };'
$replace = 'let formParams: { append(param: string, value: any): void | HttpParams; };'
(Get-Content $file).replace($find, $replace) | Set-Content $file
I would love to see a fix too !
As a temporary fix I used @itsTeknas solution on windows MinGw with a small dummy script launched on start up.
«`var runCommand = require(‘child_process’).execSync; //chose any name
var gen = ‘java -jar src/swagger/swagger-codegen-cli-2.4.13.jar generate -i src/swagger/swagger-spec.yml -l typescript-angular -o src/app/generated’;
var rxFix = ‘sed -i ‘s/rxjs/Observable/rxjs/’ ./src/app/generated/api/.service.ts’;
var frmFix = ‘sed -i «s/ || formParams//» ./src/app/generated/api/.service.ts’;
var frmFix2 = ‘sed -i ‘s/formParams = formParams/formParams/’ ./src/app/generated/api/*.service.ts’;
runCommand(gen, (error, stdout, stderr) => {
console.log(‘Output: ‘ + stdout)
if(error !== null){
console.log(«Error: » + error);
return;
}
if(stderr !== null){
console.log(«Stderr: » + stderr);
}
});
runCommand(rxFix, (error, stdout, stderr) => {
console.log(‘Output: ‘ + stdout)
if(error !== null){
console.log(«Error: » + error);
return;
}
if(stderr !== null){
console.log(«Stderr: » + stderr);
}
});
runCommand(frmFix, (error, stdout, stderr) => {
console.log(‘Output: ‘ + stdout)
if(error !== null){
console.log(«Error: » + error);
return;
}
if(stderr !== null){
console.log(«Stderr: » + stderr);
}
});
runCommand(frmFix2, (error, stdout, stderr) => {
console.log(‘Output: ‘ + stdout)
if(error !== null){
console.log(«Error: » + error);
return;
}
if(stderr !== null){
console.log(«Stderr: » + stderr);
}
});
Any news on this? Still facing the same issue…
this has been fixed by #9065 thanks everyone for help and sorry for delay.
Still have this issue with array
type form-data parameters.
Version — latest
Проблемы с типами при наследовании от абстрактного класса или при импликации от интерфейса?
Всем привет!!!
использую typescript typescript 3.1.6
почему это является корректным?
abstract class BaseUserInfo {
abstract addChangeListener(callback: (a: any) => void): void;
abstract removeChangeListener(callback: (a: any) => void): void;
abstract getState(): void;
abstract setState(newUserInfo: UserInfoModel): void;
}
export class UserInfo extends BaseUserInfo {
//...
override getState = (): UserInfoModel => {
return this.state; // type UserInfoModel
};
}
почему typescript не ругается ведь getState в дочернем и в абстрактном классе имеет разные сигнатуры
-
Вопрос задан02 авг. 2022
-
42 просмотра
Пригласить эксперта
Ну потому что extend — это «расширение», и главное совместимость, м?
В данном случае любой UserInfo
обратно совместим с BaseUserInfo
, т.к. для BaseUserInfo.getState()
возвращаемое значение имеет тип void
(не путать с undefined
), который никак не может быть использован (сам ts не даст).
abstract class BaseUserInfo {
abstract getState(): void;
}
class UserInfo extends BaseUserInfo {
override getState = (): number => 1;
}
function useInfo(info: BaseUserInfo) {
// An expression of type 'void' cannot be tested for truthiness.(1345)
if (info.getState()) { // не получится так сделать и всё сломать
console.log('never')
}
}
-
Показать ещё
Загружается…
09 февр. 2023, в 18:25
5000 руб./за проект
09 февр. 2023, в 18:23
3000 руб./за проект
09 февр. 2023, в 18:08
5000 руб./за проект
Минуточку внимания
Typescript Online Compiler
Write, Run & Share Typescript code online using OneCompiler’s Typescript online compiler for free. It’s one of the robust, feature-rich online compilers for Typescript language. Getting started with the OneCompiler’s Typescript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Typescript and start coding.
About Typescript
Typescript(JS) is a strongly typed programming language that builds on JavaScript, developed and maintained by Microsoft.
Key Features
- Superset of Javascript
- portable
- Strong static typing
- supports OOPS
- Language extension to ECMAScript 6 with other features like Type annotations and compile-time type checking, Type inference and Type erasure, Interfaces, Enumerated types, Generics, Namespaces, Tuples
- .ts extension
Syntax help
variable declaration
Keyword | Description | Scope |
---|---|---|
var | Var is used to declare variables(old way of declaring variables) | Function or global scope |
let | let is also used to declare variables(new way) | Global or block Scope |
const | const is used to declare const values. Once the value is assigned it can not be modified | Global or block Scope |
Operators
Operator | Description |
---|---|
?? |
nullish coalescing |
?. |
optional chaining |
! |
null assertion |
&&= |
used to assign value only if current value is truthy |
||= |
used to assign value only if current value is falsy |
??= |
used to assign value if current value is null or undefined |
Loops
1. If:
IF is used to execute a block of code based on a condition.
Syntax
if(condition){
// code
}
2. If-Else:
Else part is used to execute the block of code when the condition fails.
Syntax
if(condition){
// code
} else {
// code
}
3. Switch:
Switch is used to replace nested If-Else statements.
Syntax
switch(condition){
case 'value1' :
//code
break;
case 'value2' :
//code
break;
.......
default :
//code
break;
}
4. For
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
//code
}
let arr = [1, 2, 3, 4, 5];
for (let ele of arr) {
// code
}
for (let index in arr) {
//code
}
5. While
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while (condition) {
// code
}
6. Do-While
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
Arrow functions
Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.
Syntax:
() => expression
Example:
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
.map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);
Function Overloading
Typescript provides function overloading where multiple functions with the same name but different parameter types and return type is possible. But, the number of parameters should be the same.
function Addition(a:string, b:string):string;
function Addition(a:number, b:number): number;
function Addition(a: any, b:any): any {
return a + b;
}
Addition("Hello ","foo"); // outputs Hello foo
Addition(2,3); //outpus 5