我有这样的事情:
interface ISome {
myValue: number | string;
// some more members
}
我有一个函数可以接受ISome
myValue
是一个数字的function (some: ISome): number { // I accept only ISome with myValue type number
return some.myValue + 3;
}
,并使用它:
some.myValue
typescript编译器按预期抱怨,因为function (some: ISome): number { // I could use a guard
if (typeof some.myValue === "number") {
return some.myValue + 3;
}
}
是数字或字符串。
当然我可以使用联合类型来检查:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
line = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.line);
sun = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.circle);
line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), line.getHeight());
canvas.drawBitmap(line, 0, 0, null);
canvas.drawBitmap(sun, 0,0, null);
Log.d("BITMAP","WIDTH:"+line.getWidth()+" HEIGHT:"+line.getHeight());
pixelAmount = new int[line.getHeight()*line.getRowBytes()];
line.getPixels(pixelAmount,0,line.getWidth(),0,0,line.getWidth()-1,line.getHeight()-1);
Log.d("Line", "Pixel: " + pixelAmount.length + " Index" + 0);
Log.d("Line", "Pixel: " + pixelAmount[10] + " Index" + 0);
Log.d("Line", "Pixel: " + pixelAmount[100] + " Index" + 0);
Log.d("Line", "Pixel: " + pixelAmount[56] + " Index" + 0);
Log.d("Line", "Pixel: " + pixelAmount[76] + " Index" + 0);
}
}
但这不是我想要的,因为我经常需要这样做。
答案 0 :(得分:2)
您可以使用交集类型覆盖union类型,并在那里指定myValue
的类型:
function someFunction(some: ISome & {
myValue: number
}): number {
return some.myValue + 3; // No error
}