Home > Enterprise >  Why Generic with multiple type trigger compile-time error in visual code
Why Generic with multiple type trigger compile-time error in visual code

Time:10-09

I am trying to create a generic type function that take one parameter with multiple.

This should be easy but when I mix some types together then I get compile-time in visual code.

See my example below

This work..

class Test<T>{
    GetValue(value: string|boolean|number|undefined) {
        return value;
    }
}

new Test<Item>().getValue(4)
new Test<Item>().getValue(true)

This also work

    class Test<T>{
        GetValue<B>(value: (x: T) => B) {
            return value;
        }
    }

    new Test<Item>().getValue(x=> x.name)

But this dose not work. Why?

    class Test<T>{
        GetValue<B>(value: (x: T) => B|string|boolean|number|undefined) {
            return value;
        }
    }
    // this work
    new Test<Item>().getValue(x=> x.name)
    
    // this do not work Why is that?
    new Test<Item>().getValue(true)

CodePudding user response:

Operator precedence issue:

(x: T) => B|string|boolean|number|undefined

should be:

((x: T) => B)|string|boolean|number|undefined

Otherwise parameter value is considered a function that returns B|string|boolean|number|undefined

playground

  • Related