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 (
<button onClick={onClick} disabled={disabled} style={style}>
{children}
</button>
);
};
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); // OK
printId('202'); // OK
5.类型断言
/* 类型断言 */
export type Position = 'left' | 'right' | 'top' | 'bottom';
const setPos = (pos: Position) => {
//...
};
const handleChange = (value: string) => {
setPos(value as Position);
};
handleChange('left');
6.属性名不确定的对象
/* 属性名不确定的对象 */
export type Paths = {
[key: string]: string;
};
// 等同于
// export type Paths = Record<string, string>;
const paths: Paths = {};
paths.home = '/home'; //OK
paths.settings = '/settings'; //OK
paths.somePath = '/somePath'; //OK
7.对象的 key 值
/* 对象的 key 值 */
export const ErrorMessage = {
0: "success",
7: "Permission denied",
9: "Invalid parameters"
//...
};
export type ErrorCode = keyof typeof ErrorMessage;
export const logErrMsg = (code: ErrorCode) => {
console.log(ErrorMessage[code]);
};
更多关于前端培训的问题,欢迎咨询千锋教育在线名师,如果想要了解我们的师资、课程、项目实操的话可以点击咨询课程顾问,获取试听资格来试听我们的课程,在线零距离接触千锋教育大咖名师,让你轻松从入门到精通。