在打字稿中扩展/省略接口

问题描述 投票:0回答:1

我在接口类型下有道具列表。并希望通过如下修改扩展接口类型,

  1. 道具类型的改变

  2. 增加新领域

     interface Request {
       Id: NullProp<number>,
       Name: NullProp<string>,
       Code: NullProp<string>,
       Type: NullProp<string>,
       ValueType: NullProp<string>
     .....
     ...
     }
    

    /* 尝试实现如下 */

         interface DataRequest extends Request {
           Id: number,
           Name: string,
           Code: string,
           Type: string,
           ValueType: string,
         .....
         ...,
           DataRequestId: number,
           DataRequestType: string
           DataValueType: NullProp<string>
         }
    

正如所发现的,我们可以在派生接口上执行“省略”,但它需要一长串道具,因为我有很多这样的接口并且需要扩展类似的接口。 你能告诉我这是否应该是单独的新界面和复制道具或者 有什么方法可以扩展相同的界面吗?


NullProp ,输入 Q |空 |未定义

typescript typescript-generics typescript2.0
1个回答
2
投票

你可以把

NullProp
s 剥离成一个单独的类型:

type RemoveNullProp<T> = T extends NullProp<infer V> ? V : T;

type RequestWithoutNullProp = {
  [k in keyof Request]: RemoveNullProp<Request[k]>
}

然后使用您的额外属性扩展该类型:

interface DataRequest extends RequestWithoutNullProp {
  DataRequestId: number;
  DataRequestType: string;
  DataValueType: NullProp<string>;
}
© www.soinside.com 2019 - 2024. All rights reserved.