我想从数组中获取值作为类型,如下所示:
const chars = ['a','b','c'] as const
type TChars = typeof chars[number] // 'a'| 'b' | 'c'
除了 class
方法和属性,我也想这样做,如下所示:
class Test{
constructor(public chars:string[]){}
get(char:string){
return char
}
}
new Test(['a','b','c']).get('d') //error only allow a,b or c
因此 get()
方法应该只允许将初始字符传递给 constructor
。
我愿意重构类签名。
最佳答案
几乎完全相同的方式,除了您需要使类成为泛型,然后使用该泛型告诉 get
只接受数组中的值。
class Test<T extends readonly string[]> {
constructor(public chars: T) {}
get(char: T[number]) {
return char;
}
}
//error only allow a,b or c
new Test(["a", "b", "c"] as const).get("d");
关于typescript - 类方法的数组动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66067058/