我正在尝试编写一个返回值的函数,或者如果该值为null或未定义,则应返回一个默认值。
Type 'A' is not assignable to type 'B | NonNullable<A>'.
Type 'A' is not assignable to type 'NonNullable<A>'.
我收到错误
import java.util.Scanner;
public class Practise2{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int ArrForN[] = new int[n];
int ArrForM[] = new int[m];
int numb = 0 , pass = 1, store = 0 , val = 1 ;
for(int i = 0; i < n; i++)
ArrForN[i] = scan.nextInt();
for(int j = 0; j < m ; m++)
ArrForM[j] = j+1;
int y = 0;
for(int x = 0 ; x < n ; x++){
if(x < val*m) {
if(ArrForN[x] == 0){
ArrForN[x] = ArrForM[y];
numb++ ;
pass = pass* numb;
store = pass;
System.out.println(store);
y++ ;
}
else if(ArrForN[x] != 0)
y++ ;
}
else if(x == val*m){
if(ArrForN[x] == 0){
System.out.println(store);
val++ ;
numb = 0;
pass = 0;
y = 0;
ArrForN[x] = ArrForM[y];
numb++ ;
pass = pass* numb;
store = pass;
System.out.println(store);
y++ ;
}
else if(ArrForN[x] != 0)
y++ ;
}
}
}
}
NonNullable应该为A,不能为null或未定义,这就是我在if中检查的内容吗?
答案 0 :(得分:1)
条件类型(其中NonNullable
是)通常不能在泛型函数中提供良好的实现。您可以使用类型断言来使其生效(return input as any
);
一种更安全的方法可能是稍微改变一下类型:
function test<A, B>(input: A | undefined | null, fallbackValue: B): A | B {
if (input == null || input == undefined) {
return fallbackValue;
} else {
return input;
}
}
declare var s: string | null;
let a = test(s, "") // string