首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用映射类型来确保表示所有嵌套的子级?

如何使用映射类型来确保表示所有嵌套的子级?
EN

Stack Overflow用户
提问于 2022-09-14 06:38:54
回答 1查看 24关注 0票数 0

给定类型和变量:

代码语言:javascript
运行
复制
type Form = {
  controls: {
    [key: string]: any;
  }
}

const form: Form = {
  controls: {
    firstName: {},
    lastName: {},
  },
};

我想要创建一个类型,它是一个包含form.controls所有键的对象,其值类型为string,即:

代码语言:javascript
运行
复制
const formControlsWithStrings = {
  firstName: 'foo',
  lastName: 'bar',
};

我试过这样做:

代码语言:javascript
运行
复制
type FormControlsWithStrings<T extends Form> = 
 { [key in keyof T['controls']] : string }

但是,如果我在上面使用它来键入formControlsWithStrings,它会强制使用string值类型,但并不是这些键是等价的,-it不需要所有的键都存在,而且我可以添加新的键。

为什么这不起作用,我怎么才能让它起作用?

谢谢

Stackblitz:https://stackblitz.com/edit/typescript-sxvspk?file=index.ts

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-14 06:48:21

这是因为form的类型是Form,它允许任何string键。

如果让TS推断form的类型,那么它就会像预期的那样工作:

代码语言:javascript
运行
复制
type Form = {
  controls: {
    [key: string]: any;
  };
};

const form = {
  controls: {
    firstName: {},
    lastName: {},
  },
};

type FormControlsWithStrings<T extends Form> = {
  [key in keyof T['controls']]: string;
};

const formControlsWithStrings: FormControlsWithStrings<typeof form> = {
  firstName: 'abc',
  // lastName: 'def' // should not compile when commmented as it a key of form
  foo: 'bar', // should not compile as it is not present in form variable
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73712489

复制
相关文章

相似问题

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