jokcylou
jokcylou

Reputation: 113

Argument of type 'Events' is not assignable to parameter of type

interface Test {
    on(event: 'a', listener: (stats: string) => void)
    on(event: 'b' | 'c', listener: (stats: string) => void)
}

const test: Test = {
    on(event, listener) {}
}

type Events = 'a' | 'b' | 'c'
const arr: Events[] = ['a', 'b', 'c']
arr.forEach(e => {
    test.on(e, () => { })
})

code like this in typescript, when I try to bind events to test object, it will fire error which message like this:

Argument of type 'Events' is not assignable to parameter of type '"b" | "c"'. Type '"a"' is not assignable to type '"b" | "c"'.

what should I do to avoid this kind error?

Upvotes: 2

Views: 8811

Answers (1)

Fenton
Fenton

Reputation: 250892

e is an 'a' | 'b' | 'c', not an 'a', not a 'b' | 'c'. Although each value will be compatible with one of the overloads, the type is not.

You can fix this by allowing the full type (you don't need any overloads if you do this as it handles all three cases):

on(event: 'a' | 'b' | 'c', listener: (stats: string) => void)

Or by narrowing the type before you call the on method:

type Events = 'a' | 'b' | 'c'
const arr: Events[] = ['a', 'b', 'c']
arr.forEach(e => {
    if (e === 'a') {
        test.on(e, () => { })
    } else {
        test.on(e, () => { })
    }
})

Upvotes: 1

Related Questions