Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Function Arguments flaw in Typescript implementations #281

Open
bmcminn opened this issue Jan 10, 2020 · 0 comments
Open

Function Arguments flaw in Typescript implementations #281

bmcminn opened this issue Jan 10, 2020 · 0 comments

Comments

@bmcminn
Copy link

@bmcminn bmcminn commented Jan 10, 2020

I'm pointing out a "gotcha" in relation to @ryanmcdermott's comment at the end of #199 in regards to objects as function argument configs.

I agree wholeheartedly with points 1-3 and they have greatly improved some of the readability and usability of some of my personal projects. However, I build an Angular6/Typescript project at work and recently had an opportunity to leverage this approach and here's what I found.

Three years since that comment has apparently yielded some concrete ammunition against your thesis on this approach in virtually all situations in Typescript.

function createSquare({ width, color }) {
  let width = width || 0
  let color = color || 'white'

  // ...
}

let newSquare = createSquare({ width: 123 })

This will cause Typescript to throw a compilation error: error TS2345: Argument of type '{ width: 123 }' is not assignable to parameter of type '{ width: any; color: any; }'. as this appears to violate Typescripts deterministic validation of your code.

The work around to this in Typescript requires at least an interface of the methods argument object signature. As a JS purist, I hate this because it obfuscates your method signature away from your implementation in the code, but if you're using a sophisticated enough IDE then technically intellisense/autocomplete would handle the issue for you and DocBlock comments could easily handle explaining the situation, but it just feels bad to me :P

// excerpted from https://www.typescriptlang.org/docs/handbook/interfaces.html

interface SquareConfig {
  width: number;
  color?: string;
}

function createSquare(params: SquareConfig) {
  let { width, color } = params

  // ...
}

let newSquare = createSquarey({ width: 123, color: 'blue' })

It's still not great in my opinion compared to the inherit flexibility in native JS, but something I thought worth mentioning/discussing because this apparently is a hell of an exception to the rule.

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
1 participant
You can’t perform that action at this time.