首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >约束泛型类型T和K,其中K扩展了键值T,而T[K]是布尔值?

约束泛型类型T和K,其中K扩展了键值T,而T[K]是布尔值?
EN

Stack Overflow用户
提问于 2017-07-09 18:41:16
回答 1查看 226关注 0票数 1

如果不在某个地方使用any,我无法检查下面的函数类型。

代码语言:javascript
运行
复制
export function makeToggleState<T, K extends keyof T>(obj: {new(): T}, prop: K) {
  return (state: T, show: boolean|null = null) => {
    if (show === null) {
      state[prop] = !state[prop]
    } else {
      state[prop] = show
    }
  }
}

class State {
    value = true
}

makeToggleState(State, 'value')

我得到了这个错误:

代码语言:javascript
运行
复制
Type 'false' is not assignable to type 'T[K]'.
  Type 'false' is not assignable to type 'T[string]'.
(parameter) prop: K extends keyof T

告诉编译器我需要K extends keyof TT[K] is boolean的最好方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-09 23:54:37

没有办法在状态声明中使用这个约束,但是您可以为它返回的函数声明它,使用T和mapped type T & {[n in K]: boolean}的交集作为状态参数。

代码语言:javascript
运行
复制
export function makeToggleState<T, K extends keyof T>(obj: {new(): T}, prop: K) {
    return (state: T & {[n in K]: boolean}, show: boolean|null = null) => {
    if (show === null) {
      state[prop] = !state[prop]
    } else {
      state[prop] = show
    }
  }
}

class State {
    value = true;
    name = 'q';
}

const toggleValue = makeToggleState(State, 'value');

const s = new State();
toggleValue(s)


const toggleName = makeToggleState(State, 'name'); // ok

// but does not compile when you try to use it
toggleName(s);

//Argument of type 'State' is not assignable to parameter of type 'State & { name: boolean; }'.
//  Type 'State' is not assignable to type '{ name: boolean; }'.
//    Types of property 'name' are incompatible.
//      Type 'string' is not assignable to type 'boolean'.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44995497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档