javascript - TypeScript - 强制执行对象中特定键的类型

标签 javascript typescript

我正在使用 typescript ,现在正在定义一个看起来像这样的界面:

interface SelectProps<T> {
    options: T[];
    labelKey: keyof T;
    valueKey: keyof T;
}

T 可以是任何形式的对象,但它必须包含字符串的标签和键,所以我想强制执行 T[labelKey]T[valueKey] 成为字符串。我该怎么做?

最佳答案

type Option<LabelKey extends string, ValueKey extends string> = 
    Record<string, any> & Record<LabelKey | ValueKey, string>

interface SelectProps<LabelKey extends string, ValueKey extends string> {
    options: Option<LabelKey, ValueKey>[];
    labelKey: LabelKey;
    valueKey: ValueKey;
}

const props: SelectProps<'foo', 'bar'> = {
  options: [{ foo: '', bar: '', extra: 3 }],
  labelKey: 'foo',
  valueKey: 'bar'
}

关于javascript - TypeScript - 强制执行对象中特定键的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58691242/

相关文章:

javascript - typesafe 使用 reactjs 和 typescript 选择 onChange 事件

typescript - 声明泛型类型的 const

javascript - 是否可以将 Excel 工作表中的数据提供给 Chartist.js?

javascript - 如何访问jquery对象数据

javascript - React Native 场景不会根据 Parse Promise 进行更新

angular - 如何使用异步管道检查在 View 中呈现的 Observable 的长度

html - 如何使用 TypeScript 克隆包含 Angular 选择器的节点?

javascript - 向选定的 div 添加一个类,用于比较输入值和数据函数

迭代两个数组进行命中检测时出现 Javascript 错误

reactjs - HandlingChange 输入 REACTJS + TypeScript 错误