Skip to content
webtype.orgwebtype.orgTS1015

    ↑↓ move · ⏎ open · esc close

    TS1015

    Question mark and default

    Parameter cannot have question mark and initializer.

    The compiler’s own words. Not translated — this is the string you pasted into a search box.

    A default value already makes a parameter optional, so the question mark is not merely redundant — it contradicts the guarantee the default is there to give.

    Reproduction

    function greet(name?: string = 'world') {
      return name.toUpperCase()
    }

    The build asserts this emits exactly this code.

    Why the compiler says this

    The two marks make different promises about the same parameter. `?` says the argument may be left out, and that inside the body the parameter may therefore be `undefined`. `= "world"` says the argument may be left out and the parameter will be `"world"` instead — never `undefined`. The body can only be checked against one of those, so TypeScript refuses to record both and asks which one you meant.

    Fixes

    1. 01
      function greet(name: string = 'world') {
        return name.toUpperCase()
      }

      Keep the default and drop the question mark. The parameter is still optional at the call site; it is simply never `undefined` inside.

    2. 02
      function greet(name?: string) {
        return (name ?? 'world').toUpperCase()
      }

      Or keep the question mark and handle the absence yourself. Choose this when the body needs to know whether the caller said anything at all.

    Takeaway

    A default is the stronger promise: optional at the call site, never `undefined` inside. The question mark only buys a case you then have to handle.

    Where to go next

    Errors