TypeScript Básico
Volver a clases
Desarrollo Móvil●●Intermedio

TypeScript Básico

120 min
3 vistas

Tipos, interfaces y componentes con TypeScript en React Native.

¿Por qué TypeScript?

  • Prevención de errores comunes y tipado estático.
typescript
1function calculateTotal(price: number, quantity: number): number {
2  return price * quantity;
3}
4// calculateTotal("50", "2"); // ❌ Error de compilación
5// calculateTotal(50, 2); // ✅ 100

Tipos Básicos y Arrays

typescript
1let userName: string = "Ana";
2let age: number = 28;
3let isActive: boolean = true;
4let numbers: number[] = [1, 2, 3];
5let names: Array<string> = ["Ana", "Luis"];
6let coordinate: [number, number] = [10.5, 20.3];
7let id: string | number = 123;
8let status: "active" | "inactive" | "pending" = "active";

Interfaces y Types

typescript
1interface User {
2  id: number;
3  name: string;
4  email: string;
5  age?: number;
6  isAdmin: boolean;
7}
8const user: User = {
9  id: 1,
10  name: "Pedro",
11  email: "pedro@example.com",
12  isAdmin: false,
13};
14type Product = { id: number; name: string; price: number };
15type DiscountedProduct = Product & { discount: number; finalPrice: number };
16interface Animal {
17  name: string;
18  age: number;
19}
20interface Dog extends Animal {
21  breed: string;
22  bark: () => void;
23}

Componentes con TypeScript

typescript
1import { View, Text, StyleSheet } from "react-native";
2import { FC } from "react";
3interface ProfileCardProps {
4  name: string;
5  bio: string;
6  imageUrl: string;
7  followers: number;
8  onFollow: () => void;
9}
10const ProfileCard: FC<ProfileCardProps> = ({ name, bio, imageUrl, followers, onFollow }) => {
11  return (
12    <View style={styles.container}>
13      <Image source={{ uri: imageUrl }} style={styles.avatar} />
14      <Text style={styles.name}>{name}</Text>
15      <Text style={styles.bio}>{bio}</Text>
16      <Text style={styles.followers}>{followers} seguidores</Text>
17      <Button title="Seguir" onPress={onFollow} />
18    </View>
19  );
20};