0

For example, can I do the following:

const execute = (a, c = a.b) => {
// some logic
}

c is the parameter whose default value I want to set, and the default value depends on the first argument.

Can I also do the reverse? (I guess not?)

const execute = (c = a.b, a) => {
// some logic
}

1 Answer 1

1

The first form is no problem. It can even infer the type of c from a.b.

const execute1 = (a: { b: number}, c = a.b) => {
    console.log(a, c)
}
execute1({ b: 123 }) // { b: 123 }, 123

However, the second one won't work. When c is being assigned, a has not been assigned yet. So the compiler complains at you:

// Error: Parameter 'c' cannot reference identifier 'a' declared after it.(2373)
const execute2 = (c: number = a.b, a: { b: number }) => {
    console.log(a, c)
}

Typescript Playground with code

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.