我正在构建一个接收结构化对象作为参数的方法:
class MyPoint() {
...
set({ x = this.x, y = this.y, z = this.z }) {
this.x = x;
this.y = y;
this.z = z;
}
}
事情是我对它很满意,但我发现了一个没有被Typescript缓存的类型错误:
const myPoint = new MyPoint();
myPoint.set(1);
Typescript将其视为有效,因为1
确实是一个包含x
,y
或z
的对象。
要捕获此错误,我想告诉typescript:此对象可以有三个可选属性:x
,y
或z
但必须具有至少其中一个。这三个都是可选的,但必须至少定义一个。有可能吗?
答案 0 :(得分:0)
我发现的解决方案非常详细但现在有效,希望有更好的方法:
public class First extends Activity {
Button btnnext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
btnnext = (Button) findViewById(R.id.next);
btnnext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
storeTime();
Intent intent=new Intent(First.this,MainActivity.class);
startActivity(intent);
finish();
}
});
}
private void storeTime() {
SharedPreferences prefs = this.getSharedPreferences("time", Context.MODE_PRIVATE);
long currentTime = new Date().getTime();
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("time", currentTime);
editor.apply();
}
}
现在错误很明显:
interface IXSetter {
x: number;
y?: number;
z?: number;
}
interface IYSetter {
x?: number;
y: number;
z?: number;
}
interface IZSetter {
x?: number;
y?: number;
z: number;
}
type PointSetter = IXSetter | IYSetter | IZSetter;
class MyPoint() {
...
set({ x = this.x, y = this.y, z = this.z }: PointSetter) {
this.x = x;
this.y = y;
this.z = z;
}
}