15个Typescript项目常用语法练习,学会它,90%的场景不害怕!(二)
1.泛型 generics
/* 泛型 generics */
type UseState = <T>(v: T) => [T, (v: T) => void];
const useState: UseState = (v) => {
return [
v,
(v) => {
//...
}
];
};
export const Component = () => {
const [num, setNum] = useState(0); // OK
const [str, setStr] = useState(""); // OK
const [list, setList] = useState([1, 2, 3]); // OK
// test
const newNum = num + 1;
setNum(newNum);
const newStr = str.toUpperCase();
setStr(newStr);
const newList = list.slice(1);
setList(newList);
};
2.部分对象 Partial
/* 部分对象 Partial */
interface User {
name: string;
age: number;
occupation: string;
}
export const users: User[] = [
{
name: "Max Mustermann",
age: 25,
occupation: "Chimney sweep"
},
{
name: "Wilson",
age: 23,
occupation: "Ball"
}
];
type Criteria = {
[Property in keyof User]?: User[Property];
};
// 等同于
// type Criteria = Partial<User>;
export const filterUsers = (users: User[], criteria: Criteria): User[] =>
users.filter((user) => {
const criteriaKeys = Object.keys(criteria) as (keyof Criteria)[];
return criteriaKeys.every((fieldName) => {
return user[fieldName] === criteria[fieldName];
});
});
const usersOfAge23 = filterUsers(users, {
age: 23
});
3.函数中 this 的使用
/* 函数中 this 的使用 */
// 参考 https://www.typescriptlang.org/docs/handbook/2/functions.html#declaring-this-in-a-function
export const debounce = <F extends (...args: any[]) => void>(
fn: F,
delay = 200
) => {
let timeout = 0;
return function (this: any, ...args: any[]) {
timeout && clearTimeout(timeout);
timeout = window.setTimeout(() => {
fn.apply(this, args);
}, delay);
} as F;
};
4.类型编程-从基础类型构造新类型
/* 类型编程-从基础类型构造新类型 */
export type CustomObject<K extends string | number, T> = { [key in K]: T };
// 1. 示例
// ObjectOfStringValue 对象的值只能为字符串类型
type ObjectOfStringValue = CustomObject<string, string>;
const objOfStringValue: ObjectOfStringValue = {
h: "hello", // OK
w: "world" // OK
};
// 2. ObjectOfStringValue
// ObjectOfStringValue 对象的值只能为数字类型
type ObjectOfNumberValue = CustomObject<string, number>;
const objOfNumberValue: ObjectOfNumberValue = {
a: 100, // OK
b: 100 // OK
};
const a = objOfNumberValue.a;
// 3. ObjectOfUserValue
type User = {
username: string;
age: number;
};
// ObjectOfUserValue 对象的值只能为User类型
type ObjectOfUserValue = CustomObject<string, User>;
const objOfUserValue: ObjectOfUserValue = {
u1: {
username: "xiaoming",
age: 18
}
};
const { username } = objOfUserValue.u1;
5.对象类型的继承
/* 对象类型的继承 */
export interface Response {
data: any;
status: number;
statusText: string;
}
// 1. 在 Response 类型的基础上添加 config 属性
export interface ResponseWithConfig extends Response {
config: any;
}
const responseWithConfig: ResponseWithConfig = {
data: 100,
status: 0,
statusText: "success",
config: {}
};
// 2. 在 Response 类型的基础上改写 data 属性类型
export interface StringResponse extends Response {
data: string;
}
const stringResponse: StringResponse = {
data: "100",
status: 0,
statusText: "success"
};
6.对象类型的修改
/* 对象类型的修改 */
/* extends可以继承对象类型,但不可与原类型冲突,此时可以先使用 Omit 去除需要修改的属性 */
export interface TreeNode {
id: number;
value: number;
children?: TreeNode[];
}
// 1. 去除 TreeNode 的 id 属性同时修改 children 属性的类型
export interface NodeWithoutId extends Omit<TreeNode, "id" | "children"> {
children?: NodeWithoutId[];
}
// OK
const nodeWithoutId: NodeWithoutId = {
value: 1,
children: [
{
value: 2
}
]
};
7.类型编程-条件判断
/* 类型编程-条件判断 */
export declare type Person<T extends "User" | "Admin"> = T extends "User"
? {
username: string;
}
: {
username: string;
role: string;
};
const user: Person<"User"> = { username: "xiaoming" }; // OK
const admin: Person<"Admin"> = { username: "xiaofang", role: "manager" }; // OK
8.React 组件 Props 范型
/* React 组件 Props 范型 */
import { useState } from "react";
// value 可为字符串或数字
type Value = number | string;
interface Props<T extends Value> {
value?: T;
onChange?: (v: T) => void;
type?: "number" | "text";
}
const Input = <T extends Value>({
value,
onChange,
type = "text"
}: Props<T>) => {
return (
<input
value={value}
onChange={(e) => {
const { value } = e.target;
onChange?.((type === "number" ? parseInt(value, 10) : value) as T);
}}
type={type}
/>
);
};
// test
const Test = () => {
const [num, setNum] = useState(0);
const [str, setStr] = useState("");
return (
<div>
<Input value={num} onChange={(v) => setNum(v)} type="number" />
<Input value={str} onChange={(v) => setStr(v)} />
</div>
);
};
export default Input;
更多关于前端培训的问题,欢迎咨询千锋教育在线名师,如果想要了解我们的师资、课程、项目实操的话可以点击咨询课程顾问,获取试听资格来试听我们的课程,在线零距离接触千锋教育大咖名师,让你轻松从入门到精通。
10年以上业内强师集结,手把手带你蜕变精英
请您保持通讯畅通,专属学习老师24小时内将与您1V1沟通
今日已有369人领取成功
开班信息
北京校区
- 北京校区
- 大连校区
- 广州校区
- 成都校区
- 杭州校区
- 长沙校区
- 合肥校区
- 南京校区
- 上海校区
- 深圳校区
- 武汉校区
- 郑州校区
- 西安校区
- 青岛校区
- 重庆校区
- 太原校区
- 沈阳校区
- 北京校区
- 大连校区
- 广州校区
- 成都校区
- 杭州校区
- 长沙校区
- 合肥校区
- 南京校区
- 上海校区
- 深圳校区
- 武汉校区
- 郑州校区
- 西安校区
- 青岛校区
- 重庆校区
- 太原校区
- 沈阳校区
IT头条热榜
面试题库更多>>
Linux云计算工程师面试题汇总(二)
Linux云计算工程师面试题汇总(一)
进大厂必须掌握的python面试题(二)
进大厂必须掌握的python面试题(一)
缓存的淘汰策略有几种方式?都怎么用
Java常用开发工具之常用源码编辑工具
热搜问题
云计算培训费用多少钱?贵不贵?
沸零基础如何学html5?自学好还是参加培训好
热java培训班要多少钱
热如何选择新媒体培训机构?
新旅行自媒体如何赚钱?你知道吗?
Python就业方向怎么选择?
Python培训效果好不好?
UI设计培训费用多少钱?可靠吗
Java的就业方向是什么?
web前端可以从事哪些工作?
现在学习UI设计晚吗?
大数据培训机构有用吗
大数据培训就业情况如何?
移动App性能测试都测试什么
IT技术那个比较好就业?
北京软件测试培训多少钱?
IT前景好吗?值得学习么?
Linux云计算可以学会吗