Skip to content

Named arguments  #39860

Closed
Closed
@d8corp

Description

@d8corp

name: Feature Request
about: Suggest an idea
title: 'Named arguments'
labels: 'Named arguments'
assignees: 'somebody'


Search Terms

  • Named arguments

Suggestion

Now we can use an object to provide named arguments.

function test ({x = 1, y = 2}) {}

But we should create an object to use this.

test({y: 1})

Also, we should add default value equals to an empty object when all fields are optional.

function test ({x = 1, y = 2} = {}) {}

I really don't like it.
I would like to see the simplest way to use named arguments.

function test (x = 1, y = 2) {}

test(y: 1)

This converts to ES like

function test (x = 1, y = 2) {}

test(void 0, 1)

It does not replace the named object arguments, just the sugar for positional arguments.

Use Cases

This is a great feature if we use a couple of optional arguments.

function get (weight?: number, height?: number, top?: number, left?: number) {...}

get(top: 42)
get(height: 13)
get(left: 13)

We could change it to

get(,, 42)
get(, 13)
get(,,, 13)

But, the named argument looks most understandable.
Also, this is a great feature to lock the sense of the argument.
Let's change the order of the get function arguments

// function get (weight?: number, height?: number, top?: number, left?: number) {...}
function get (top?: number, left?: number, weight?: number, height?: number) {...}

get(top: 42) // Ok
get(height: 13) // Ok
get(left: 13) // Ok

get(,, 42) // Bug
get(, 13) // Bug
get(,,, 13) // Bug

Or we can change a couple of argument sense

// function get (weight?: number, height?: number, top?: number, left?: number) {...}
function get (top?: number, right?: number, bottom?: number, left?: number) {...}

get(top: 42) // Ok
get(height: 13) // Error
get(left: 13) // Ok

get(,, 42) // Bug
get(, 13) // Bug
get(,,, 13) // Ok

That's why TypeScript was born.

Examples

function setPosition (top?: number, left?: number, ... elements: Element[]) {...}

const element1 = document.createElement('div')
setPosition(top: 0, elements: [element1])

const element2 = document.createElement('span')
setPosition(left: 0, elements: [element1, element2])

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions