V
V
VovaSakay2021-05-23 13:42:44
typescript
VovaSakay, 2021-05-23 13:42:44

How to type a method?

Now Challenge
public get<T>(prop: Constants): T {}

const VERTICAL = 'vertical';
const STEP = 'step';

this.model.get(VERTICAL) // VERTICAL значит должен возвращать только boolean
this.model.get(STEP) // STEP значит должен возвращать только number

How do I type the get method so that it returns a data type based on a constant?
// это не предлагать)
<boolean>this.model.get(VERTICAL) 
<number>this.model.get(STEP)


I did the same with the add method
public add({ value, prop }: ActionsModel): void { }

interface Action<T> {
  prop: T;
}
interface ActionPayload<T, Y> extends Action<T> {
  value: Y;
}
type ActionStep = ActionPayload<Constants.STEP, number>;
type ActionVertical = ActionPayload<Constants.VERTICAL, boolean>;

type ActionsModel = ActionStep | ActionVertical;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2021-05-23
@VovaSakay

Can So

A
Aetae, 2021-05-23
@Aetae

I would like to know what kind of Constants is, perhaps everything can be made simpler.
But conditionally - something like this:

enum Constants {
  VERTICAL = 'vertical',
  STEP = 'step'
}

interface ConstantsTypes {
  [Constants.VERTICAL]: boolean,
  [Constants.STEP]: number,
}

public get<T extends keyof ConstantsTypes>(prop: T): ConstantsTypes[T] {}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question