总结了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);
总结了15道Typescript项目常用语法练习,学会它,90%的场景都不再害怕!
最新推荐文章于 2024-05-10 15:10:20 发布
本文详细介绍了15个在Typescript项目中常用的语法练习,包括基本类型、React组件Props、联合类型、类型判断、类型断言等,通过这些实践,能够帮助开发者掌握90%以上的场景应用。
摘要由CSDN通过智能技术生成