3

I'm very new to TypeScript and React, so apologies for any incorrect or confusing terminology. Basically this is what I'm looking at:

<MyComponent someNumber="40" />

someNumber is a property defined as number, but I'm noticing the following behavior:

  • If I pass a non-number value, e.g. <MyComponent someNumber="foo" /> this still compiles but blows up at runtime
  • If I fail to pass any value, e.g. <MyComponent /> this still compiles even if there's no default value for someNumber

Ideally those two scenarios should fail to compile, but I don't see a way to do this. I'm on TypeScript 2.0.6 if it helps.

This is my tsconfig.json:

{
  "compilerOptions": {
    "outDir": "./dist",
    "allowJs": false,
    "target": "es6",
    "module": "commonjs",
    "jsx": "react"
  },
  "include": [
    "./src/**/*"
  ],
  "files": [
    "typings/index.d.ts"
  ]
}

1 Answer 1

4

If you define an interface for the component props then the compiler will check all of that for you:

interface MyProps {
    someNumber: number;
}
interface MyState {}
class MyComponent extends React.Component<MyProps, MyState> {}

let a1 = <MyComponent someNumber={ 40 } />; // fine
let a2 = <MyComponent />; // Error: Property 'someNumber' is missing in type ...
let a3 = <MyComponent someNumber="40" />; // Error: Type 'string' is not assignable to type 'number'

Edit

The problem had something to do with the react definition files the OP was using.
Installing the definition using:

npm install @types/react

Solved the problem.

9
  • I am actually doing that now, but I'm referencing MyComponent from an external file. Still not getting any errors though. For reference, this is the example I'm working on: * Instantiation: github.com/rolodato/volca-keys-editor/blob/… * Definition: github.com/rolodato/volca-keys-editor/blob/… Oct 28, 2016 at 21:03
  • I've also tried instantiating an invalid component in the same file that it's defined in, still not getting any errors from the compiler though. Oct 28, 2016 at 21:14
  • 2
    Using version 2.0.3 I'm getting A LOT of errors trying to compile your code. Things like: Type 'string' is not assignable to type 'number' and Property 'initialValue' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<Parameter> & Props & { children?: ReactNode; }'. Please update your question with your tsconfig.json file Oct 28, 2016 at 21:14
  • Strange, it compiles just fine on my end. Added the tsconfig.json to the question. Oct 28, 2016 at 21:16
  • It looks ok. How are you compiling? tsc from command line? Inside an IDE? Oct 28, 2016 at 21:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.