打字稿检查对象是否包含许多属性中的一个

时间:2017-05-18 09:48:02

标签: typescript destructuring

我正在构建一个接收结构化对象作为参数的方法:

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确实是一个包含xyz的对象。

要捕获此错误,我想告诉typescript:此对象可以有三个可选属性:xyz必须具有至少其中一个。这三个都是可选的,但必须至少定义一个。有可能吗?

1 个答案:

答案 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;
  }
}