总结了15道Typescript项目常用语法练习,学会它,90%的场景都不再害怕!

本文详细介绍了15个在Typescript项目中常用的语法练习,包括基本类型、React组件Props、联合类型、类型判断、类型断言等,通过这些实践,能够帮助开发者掌握90%以上的场景应用。
摘要由CSDN通过智能技术生成

总结了15道Typescript项目常用语法练习,学会它,90%的场景都不再害怕!
1.常用类型
/* 常用类型*/

// 1. string 字符串类型
export const str: string = “helloworld”;
str.substr(3);

// 2. number 数字类型
let num: number = 100;
num++;

// 3. boolean 布尔类型
const bool: boolean = true;

// 4. 数组类型
const numArr: number[] = [1, 2, 3];
numArr.map((num) => ++num);

// 5. 对象类型
type User = {
 name: string;
 age: number;
 isAdmin: boolean;
};
const user: User = {
 name: “xiaoming”,
 age: 18,
 isAdmin: false
};
const { name, age, isAdmin } = user;

// 6. 函数类型
type Fn = (n: number) => number;
const fn: Fn = (num) => ++num;
fn(1);
2、React 组件 Props
/* React 组件 Props /

interface Props {
 disabled?: boolean;
 style?: React.CSSProperties;
 children?: React.ReactNode;
 onClick?: () => void;
}

const Button = ({ onClick, disabled, children, style }: Props) => {
 return (
   
    {children}
   
);
};

export default Button;
3.联合类型 Union
/
联合类型 Union /

// id 可为字符串或数字类型
export function printId(id: string | number) {
 console.log(id);
}

printId(101); // OK
printId(‘202’); // OK
4.类型判断
/
类型判断 /

export function printId(id: string | number) {
 if (typeof id === ‘string’) {
   console.log(id.toUpperCase());
} else {
   console.log(id);
}
}

printId(101);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值