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]);
};
更多關于前端培訓的問題,歡迎咨詢千鋒教育在線名師,如果想要了解我們的師資、課程、項目實操的話可以點擊咨詢課程顧問,獲取試聽資格來試聽我們的課程,在線零距離接觸千鋒教育大咖名師,讓你輕松從入門到精通。