Home > database >  JavaScript checking vs Typescript
JavaScript checking vs Typescript

Time:11-21

I have the next code in my react js application:

interface Input {
  name: string;
  type?: 'email' | 'text';
}

const Input = ({type}: Input) => {

return <input type={type}/>
}

The component can receive only type email and text. If the user will add as a prop number then the compiler will throw an error in compilation time. EX:

<Input type="number"/>
Type '"password"' is not assignable to type '"text" | "email". 

, but in the same time we can anyway to type:

<Input type="number"/>

even with this error and to suppress the error.
Question: Should i restrict the type props only using typescript like in my case or should i use javascript to exclude the situation when the type will be number?

CodePudding user response:

It's a tradeoff of safety, speed, and your own development time. You'll need to decide this based on your use-case: it's a matter of judgment, not of universal best practice. Though runtime checks would make your code safer and more complete to test at runtime, it may not provide much value for a component for which you're the only user, and that you use a limited number of times.

I could see it going either way here; you'll need to decide based on your understanding of the benefits and costs.

Good times to add extra defensive checks even when TypeScript makes errors unlikely:

  • in migrated codebases where there is a lot of usage of any, implicit or explicit
  • in large codebases with external users or lots of internal users
  • where stakes are high: the component is critical or a misuse would introduce subtle errors later
  • in component initialization or cases that happen infrequently per application, where the overhead of an extra check is negligible
  • for values that are frequently dynamic or user-supplied, like value
  • where automated tests elsewhere are difficult, or unlikely to catch this

Conversely, runtime defensive checks may be overkill in these cases:

  • where use of TypeScript is endemic: it's very unlikely someone would override a type check
  • in small codebases where you might be the only one calling this
  • in low-stakes environments, either because the behavior is obviously wrong or it has minimal consequences
  • in tight inner loops or where runtime checking would be expensive performance-wise
  • for values that are unlikely to be user-supplied, like type
  • where other testing would likely catch this

CodePudding user response:

Just add password to type in order to support it in the prop

type?: 'email' | 'text' | 'password' | 'number';
  • Related