Skip to content

Inconsistent Function Subtyping: (input?: string) => void Incorrectly Assignable to () => void #60144

Closed
@sklationd

Description

@sklationd

🔎 Search Terms

"optional function inconsistency", "runtime error with function assign", "bivariant", "strictFunctionTypes'

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about "Why are function parameters bivariant?", "Why are functions with fewer parameters assignable to functions that take more parameters?"

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/C4TwDgpgBA8gCgFQJIwHIEEAyB9AYgVVQGEoBeKACgEMAnAcwH4AuKAZ2BoEsA7OgSjIA+KADcA9pwAmAbgBQAGwjAoYsME5juVebgCu3AMYt4yNFjyES5CjzC7gzNhx78hsqB6gHNrMYoB08mJ0Ntx2Dv6s8pwGEBQADAA0UACMfHxysqCQUACiALKIAJoWxGSUAqTC4lJyisoQALZqIHqGLAXFpVYVQlAA3gC+mdnQqDAI2CYoGDgEZda29iwARmJ+EFTcldUSMgpKUNxiwDBqGlo6+kZQ45PTZnOW5aHhq+uKWztePhuBwa97BlZLImi02gZyqp1JptBDpFAAPSItgACzEunkkiOJygK2gYCorFYEEksmOp3OsKuhnKYNA8PJJzOMMuEIoHF0EAySJRNH06ka0AgNBoYhoKgMBl0NFJINkQA

💻 Code

let a = (input?: string) => input?.slice(0, 1);
let b = () => {};
let c = (input: number) => console.log(input);

b = a; // should not be okay
c = b; // okay
c(3);  // runtime error!
// c = a <- type error

🙁 Actual behavior

Assigning a function of type (input?: string) => void to a function of type () => void passes the type checker but causes a runtime error.

🙂 Expected behavior

Assigning (input?: string) => void to () => {} should trigger a type error because (input?: string) => void is not a subtype of () => {}; rather, the reverse is true. As a result, this should prevent a runtime error.

Additional information about the issue

Could this be a known issue, or is it an intentional design choice? If intentional, what is the rationale behind it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions