typescript - 类方法的数组动态类型

标签 typescript

我想从数组中获取值作为类型,如下所示:

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

我愿意重构类签名。

TS Playground

最佳答案

几乎完全相同的方式,除了您需要使类成为泛型,然后使用该泛型告诉 get 只接受数组中的值。

TS Playground

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/

相关文章:

javascript - 如何防止(单击)将该类添加到 ngFor 中的所有元素?

typescript - promise 只是返回?

typescript - 使用 npm run 时是否使用了不同版本的 tsc?

javascript - Protocol Buffer : Uncaught reference error: exports is not defined

typescript - 如何在 Typescript 函数类型中强制执行强制参数?

typescript - 使用 ES6 集合类型创建和发布 NPM 模块

angular - 使用自动完成和 "updateOn: ' 模糊时防止提前验证'”

reactjs - @符号在react import语句中意味着什么

javascript - 模块未在 node_modules/core-js/internals/global.js 中定义

Angular 2 : How to bind Input to model property with getter and setter methods?