【问题标题】:有没有办法强制两种类型具有相同的键?
【发布时间】:2022-01-23 16:57:42
【问题描述】:

例如,我希望以下两种类型 - ViewModel 和 SaveModel 具有相同的键但不同的值类型,

type User = {
  id: number;
  name: string; 
  age: number;
}

type Address = {
  street: string; 
  zip: string;
}

type ViewModel = {
  user: User;
  address: Address;
}

type SaveModel = {
  user: number;
  address: string;
}

如何在打字稿中做到这一点?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    由于 ViewModel 中的属性类型与 SaveModel 中的属性类型之间似乎没有任何关系,您可以创建一个类型来约束第二种类型以具有相同的键:

    
    type MustHaveKeys<V, S extends Record<keyof V, any>> = S;
    
    type SaveModel = MustHaveKeys<ViewModel, {
      user: number;
      address: string;
    }>
    type SaveModelBad = MustHaveKeys<ViewModel, {
      //user: number;
      address: string;
    }>
    
    

    Playground Link

    【讨论】:

    • 感谢提香·切尔尼科娃-德拉戈米尔!
    • 就我而言,我没有主/次模型,所以我稍微更改了您的示例typescriptlang.org/play?#code/…,希望先在任何模型中添加键更容易。
    • @ABOS 也可以
    猜你喜欢
    • 2019-01-10
    • 2020-02-23
    • 2014-11-10
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 2022-11-22
    • 2018-07-21
    • 2022-01-06
    相关资源
    最近更新 更多