Introduction
TypeScript is a programming language developed by Microsoft. It is a typed superset of JavaScript and includes its own compiler. Being a typed language, TypeScript can catch errors and bugs at build time, long before your app goes live.
superset of JS means that it introduces new features and expands the capabilities of JavaScript
React Native next
version will use TypeScript. New projects created by React Native CLI will use TypeScript by default.
So you don't need to
- Add TypeScript as a dependency to your project
- Configure the TypeScript compiler options
React Native + TypeScript component example
-
React.FC: It provides
typechecking
andautocomplete
for static properties likedisplayName
,propTypes
, anddefaultProps
. -
Props: An interface for a React Component's Props and State
React.Component<Props, State>
will provide type-checking and editor auto-completing when working with that component in JSX.
import React from 'react';
import {Button, Text, View} from 'react-native';
export type Props = {
name: string;
baseEnthusiasmLevel?: number;
};
const Hello: React.FC<Props> = ({
name,
baseEnthusiasmLevel = 0,
}) => {
const [enthusiasmLevel, setEnthusiasmLevel] = React.useState(
baseEnthusiasmLevel,
);
const onIncrement = () =>
setEnthusiasmLevel(enthusiasmLevel + 1);
const onDecrement = () =>
setEnthusiasmLevel(
enthusiasmLevel > 0 ? enthusiasmLevel - 1 : 0,
);
const getExclamationMarks = (numChars: number) =>
numChars > 0 ? Array(numChars + 1).join('!') : '';
return (
<View>
<Text>
Hello {name}
{getExclamationMarks(enthusiasmLevel)}
</Text>
<View>
<Button
title="Increase enthusiasm"
accessibilityLabel="increment"
onPress={onIncrement}
color="blue"
/>
<Button
title="Decrease enthusiasm"
accessibilityLabel="decrement"
onPress={onDecrement}
color="red"
/>
</View>
</View>
);
};
export default Hello;
Using JavaScript instead of TypeScript
React Native defaults new applications to TypeScript, but JavaScript may still be used. Files with a .jsx
extensions are treated as JavaScript instead of TypeScript, and will not be type-checked.
Helpful links to learn TypeScript
Wrapping up
TypeScript is #5 on the list of the most popular scripting, programming, and markup languages. Also, many tech companies use TypeScript in their tech stack. So learning TypeScript in 2023 will be helpful for a front-end developer overall.
Thank you for reading!
Contact me
Top comments (1)
I need to initialize a project in React Native with Javascript only, is there a way to do that ? please help me with that !