N
N
Nikolay2019-12-03 01:56:35
typescript
Nikolay, 2019-12-03 01:56:35

How to fix this typing error?

Error:(17, 28) TS2322: Type 'number' is not assignable to type 'T'.
'number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'BuffValues'.

I made the solution `case 'number': return this._numberStep(value) as T;`, but I don't like it at all. breaks typing, is there a better way?

import { SequentialBuff } from './sequential-buff';
import { BuffSequence } from '../../../../types/buffs';
import { assertNever } from '../../../../../../utils/assert-never';

type BuffValues = number | boolean;

export abstract class UniformSequentialBuff<T extends BuffValues> extends SequentialBuff<T> {
    protected readonly _sequence: BuffSequence<BuffValues>;

    constructor(value: T, duration: number) {
        super(duration);
        this._mainValue = value;
        this._sequence = new Array(this._duration).fill(this._mainValue);
    }

    protected mutate(value?: T): T {
        switch (typeof value) {
            case 'boolean': return this._mainValue;
            case 'number': return this._numberStep(value);
            default: return assertNever('Forbidden type of the buff value!');
        }
    }

    private _numberStep(value?: number): number {
        if (typeof this._mainValue === 'number') {
            return value * this._mainValue;
        }
        assertNever('The buff value must be number!');
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2019-12-03
@tryvols

This solution does not violate typing, but vice versa - you know for sure that in this case T will contain exactly number and therefore `return this._numberStep(value)` is completely valid. But the compiler does not know, and in this way you give it a hint.
Of course, it's better if he himself could narrow T down to number in this case, but here you have to help a little.
Perhaps there is some kind of construction to sort out types automatically without as, but with a cursory reflection, nothing comes to the ready, and it will be essentially the same (let the compiler know that everything is OK) only with much more additional code.
Write as and sleep well.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question