将数组转换为打字稿选项

时间:2021-03-30 22:24:29

标签: node.js typescript

我想知道是否可以使用字符串/整数数组作为打字稿接口的选项。例如:

const numbers = [50,100,200,300,400,500];
interface INumbers {
    numbersType:numbers --> (should be 50 | 100 | 200 | 300 | 400 | 500)
}

请告诉我这是否可行以及如何做到这一点!

谢谢!

2 个答案:

答案 0 :(得分:0)

你可以这样试试。

ngOnInit() {
this. bntStyle1 = 'btn-default';
this. bntStyle2 = 'btn-default';
this. bntStyle3 = 'btn-default';
this. bntStyle4 = 'btn-default';
}

changeButton(bttn) {
if (bttn === 1 ) {
this.bntStyle1 = 'btn-change';
this.bntStyle2 = 'btn-default';
this.bntStyle3 = 'btn-default';
this.bntStyle4 = 'btn-default';
this.drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
}
if (bttn === 2 ) {
this.bntStyle1 = 'btn-default';
this.bntStyle2 = 'btn-change';
this.bntStyle3 = 'btn-default';
this.bntStyle4 = 'btn-default';
}

if (bttn === 3 ) {
this.bntStyle1 = 'btn-default';
this.bntStyle2 = 'btn-default';
this.bntStyle3 = 'btn-change';
this.bntStyle4 = 'btn-default';
}
if (bttn === 4 ) {
this.bntStyle1 = 'btn-default';
this.bntStyle2 = 'btn-default';
this.bntStyle3 = 'btn-default';
this.bntStyle4 = 'btn-change';
}


 console.log('We hit button change');

}

答案 1 :(得分:0)

const numbers = [50,100,200,300,400,500] as const;

interface INumbers {
    numbersType: (typeof numbers)[number]
}

const passes: INumbers = {
    numbersType: 50 // WORKS
};

const fails: INumbers = {
    numbersType: 51 // FAILS
};