1.常用類型
/* 常用類型*/
// 1. string 字符串類型
export const str: string = "helloworld";
str.substr(3);
// 2. number 數(shù)字類型
let num: number = 100;
num++;
// 3. boolean 布爾類型
const bool: boolean = true;
// 4. 數(shù)組類型
const numArr: number[] = [1, 2, 3];
numArr.map((num) => ++num);
// 5. 對(duì)象類型
type User = {
name: string;
age: number;
isAdmin: boolean;
};
const user: User = {
name: "xiaoming",
age: 18,
isAdmin: false
};
const { name, age, isAdmin } = user;
// 6. 函數(shù)類型
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.聯(lián)合類型 Union
/* 聯(lián)合類型 Union */
// id 可為字符串或數(shù)字類型
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.屬性名不確定的對(duì)象
/* 屬性名不確定的對(duì)象 */
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.對(duì)象的 key 值
/* 對(duì)象的 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]);
};
更多關(guān)于前端培訓(xùn)的問(wèn)題,歡迎咨詢千鋒教育在線名師,如果想要了解我們的師資、課程、項(xiàng)目實(shí)操的話可以點(diǎn)擊咨詢課程顧問(wèn),獲取試聽(tīng)資格來(lái)試聽(tīng)我們的課程,在線零距離接觸千鋒教育大咖名師,讓你輕松從入門到精通。