简体   繁体   English

Typescript接口,为动态第二个属性引用一个实例属性

[英]Typescript Interface, reference one instance property for dynamic second property

I want to use a property within a Typescript Interface's instance to compute a second property. 我想在Typescript接口实例中使用一个属性来计算第二个属性。 I've been looking into Generics but I'm not successfully implementing this yet. 我一直在研究泛型,但尚未成功实现。 :

Here's an example 这是一个例子

// Here I define all valid names - works fine!

type ModalNames = 'payment' | 'source'

// This interface implements all expected payloads
//  for each name 

interface ModalPayloads {
  payment: {
    plan: string
  }
  source: {
    metadataId: string
  }
}


// How do I use the instance name
//  to grab the correct payload property?
export interface ShowModalPayload {
  name: ModalNames
  modalProps?: ModalPayloads[instance.name]
}

In other words, for a given instance of ShowModalPayload , I want to assign modalProps to a type derived from instance.name . 换句话说,对于ShowModalPayload的给定instance ,我想将modalProps分配给从instance.name派生的类型。 Hopefully this makes sense! 希望这是有道理的!

I'd use generics for this: 我会为此使用泛型

export interface ShowModalPayload<K extends ModalNames> {
  name: K
  modalProps?: ModalPayloads[K]
}

Note the use of ModalPayloads[K] in place of ModalPayloads[instance.name] . 请注意,使用ModalPayloads[K]代替ModalPayloads[instance.name] That's called a lookup type and it allows you to describe the type of m[k] where m has type ModalPayloads and k has type K . 这称为查找类型 ,它允许您描述m[k]的类型,其中m具有ModalPayloads类型,而k具有K类型。

Anyway the ShowModalPayload interface is now generic in K , which should be one of the ModalNames literals: 无论如何, ShowModalPayload接口现在在K是通用的,它应该是ModalNames文字之一:

declare const smpPayment: ShowModalPayload<'payment'>;
smpPayment.name // "payment"
smpPayment.modalProps // {plan: string} | undefined

declare const smpSource: ShowModalPayload<'source'>;
smpSource.name // "source"
smpSource.modalProps // {metadataId: string} | undefined

Those correspond to what you're looking for, I think. 我认为这些符合您的需求。 Note that the following is still possible: 请注意,仍然可以进行以下操作:

declare const smpWhoKnows: ShowModalPayload<ModalNames>
smpWhoKnows.name // ModalNames
smpWhoKnows.modalProps // {plan: string} | {metadataId: string} | undefined

which is possibly not what you want, but is not prohibited. 这可能不是您想要的,但也不被禁止。 The above definition is probably sufficient for most use cases, though. 但是,上面的定义对于大多数用例而言可能已经足够。

Hope that helps. 希望能有所帮助。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM