Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface props in functional components

I am using the nightly-build of TypeScript (Version 1.9.0-dev.20160218), and trying to work out if there is any way to use static typed props in my functional react component.

The current code seems to give no compile errors, and works just fine. But as I have set the myvar to be of type Number, but actually assign it as a String I would have expected a compile-time error.

Does TypeScript currently support strict-types for props in functional components, or only for classes?

interface Props extends React.Props {
    mynumber: Number
}

var MyComponent = (props: Props) => {
    return <p>My variable: {props.mynumber}</p>;
};

var MyContainer = () => {
    const mystring:String = '123';
    return <MyComponent myvar={mystring}/>
};
like image 741
Etse Avatar asked May 23 '26 19:05

Etse


1 Answers

This code works as expected:

/// <reference path="../DefinitelyTyped/react/react.d.ts" />

import * as React from 'react';

interface Props extends React.Props<any> {
    mynumber: Number
}

var MyComponent = (props: Props) => {
    return <p>My variable: {props.mynumber}</p>;
};

var MyContainer = () => {
    const mystring:String = '123';
    return <MyComponent myvar={mystring}/>
};

test.tsx(15,12): error TS2324: Property 'mynumber' is missing in type 'IntrinsicAttributes & Props'. test.tsx(15,25): error TS2339: Property 'myvar' does not exist on type 'IntrinsicAttributes & Props'.

It looks like you have an outdated react.d.ts, or something else is wrong and your code sample isn't representative.

As an aside, never use String or Number. These aren't the types you want -- use string and number, respectively

like image 155
Ryan Cavanaugh Avatar answered May 26 '26 16:05

Ryan Cavanaugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!