网站搜索

typescript - 如何限制对象的键但将值推断为常量?


给定这个对象,是否有一种方法可以将其值推断为 const,同时确保键包含在 Field 联合类型中?

type Field = 'name' | 'isHappy';

const fieldTypes: { [field in Field]: string } = {
  name: 'text',
  isHappy: 'checkbox',
};

我的目标是让 fieldTypes 拥有以下类型:

{
  name: 'text';
  isHappy: 'checkbox';
}

而不是

{
  name: string;
  isHappy: string;
}

答案#1

不仅仅是变量声明。变量类型要么从赋值推断,要么通过类型注解指定,没有中间状态。

你可以改用一个函数,该函数既可以推断类型,也可以限制类型:

type Field = 'name' | 'isHappy';

function createFields<T extends Record<Field, V>, V extends string>(o: T) {
  return o;
}

const fieldTypes = createFields({
  name: 'text',
  isHappy: 'checkbox',
})

// Typed as: 
// const fieldTypes: {
//     name: "text";
//     isHappy: "checkbox";
// }

游乐场链接