I have a TypeScript interface with two properties (type:string
and args:object
). The args
may have different properties depending on the type
. What type definition to I need to apply to args
so the compiler/autocomplete will know which properties are allowed for args
?
This is somewhat similar to how I use Actions in Redux, which do have a type
and a payload
and in my reducer the compiler knows by the switch-statement what the payload contains. But I can't get this to work with my object.
I have read an excellent article here https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/ but this describes the problem for a method with two args which depend on one another but not how to get this working for two properties within the same object.
export interface IObject {
type: ObjectType
parameters: ObjectParameters
}
export type ObjectType = "check" | "counter"
export interface IParametersCheck {
checked: boolean
}
export interface IParametersCounter {
max: number
min: number
step: number
}
export type ObjectParameters = IParametersCheck | IParametersCounter
If I have an IObject
and set the type to "check" the compiler/autocomplete should offer the properties for IParametersCheck
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…