If you use atom... download & install the following packages:
You may see a folder called typings
with a lot of files that follow the pattern *.d.ts
. These are type definition files. Type definition files are used to declare the interfaces of public API of third party libraries like jQuery or React. That way you don't have to create all the typings for third party libraries!
-
Create a file using the
.tsx
extention -
Declare the interface for any props that that the React Component uses
interface TodoProps {
todo: string
status: string
}
- Declare the interface for any state that exists within the React component
interface TodoState {
isEditing?: boolean
// Make all state optional! See Hack below
}
Hack: For now make every key in state optional or else Typescript with throw an error
- Create a React component using the interfaces you created
class TodoComponent extends React.Component<TodoProps, TodoState> {
constructor(props: TodoProps) {
super(props)
this.state = { ... } // initial state
}
... // public + react methods
}
In order for Typescript to be happy, use refs inside the class like so:
class Cat extends <CatProps, {}> { // no state
refs: {
[key: string]: (Element)
litterBox: (HTMLInputElement) // !important
}
constructor(props: CatProps){ ... } // constructor
render() {
return (
<div ref="litterBox">
litter
</div>
)
}
}
A collection of types that describes the shape that a value must have
interface CatValue {
name: string
age: number
}
function petCat(cat: VatValue) {
console.log(cat.name)
}
let myCat = { name: 'Whiskers', age: 4 }
petCat(myCat) // 'Whiskers'
PROTIP: use ?
for optional values
interface CatValue {
name: string
age: number
favoriteFish?: string // optional
}
@drrudkh you should never have to declare state as a property. The members state and props are already inherited from React.Component according to the official documentation:
Instance Properties
props
state
Here: https://reactjs.org/docs/react-component.html
State is as the name implies the current state of a component instance in memory. The way I think of it is it's a mutable object that allows developers to put bound properties (variables) to that represent elements in the DOM such as user input etc. Hope that makes sense.