What is the correct interface IMyClass
which would fulfill the requirements?
interface IMyClass {
params: any
chooseParam: Function
}
class MyClass implements IMyClass {
params = ['min', 'max']
chooseParam = (oneOfParams) => {
return oneOfParams === "min" ? "something" : "something2" // <- I want to intellisense to say me that oneOfParams = "min" | "max"
}
}
//usage
const a = new MyClass()
a.chooseParam("min") // <- I want to intellisense here "min" | "max"
CodePudding user response:
Does params
have to part of the interface? Looks like it's just an argument to chooseParam
. I'd do something like this:
enum ParamOption {
Min = 'min',
Max = 'max'
}
interface IMyClass {
chooseParam: Function
}
class MyClass implements IMyClass {
chooseParam = (oneOfParams: ParamOption) => {
return oneOfParams === ParamOption.Min ? true : false
}
}
//usage
const a = new MyClass()
a.chooseParam(ParamOption.Min)
CodePudding user response:
COnsider this example:
interface IMyClass {
params: readonly [string, string]
chooseParam: Function
}
class MyClass implements IMyClass {
params = ['min', 'max'] as const
chooseParam = (oneOfParams: this['params'][number]) => {
return oneOfParams === "min" ? true : false
}
}
const a = new MyClass()
a.chooseParam('max')
this['params'][number]
- obtains a union of all values in params