11. Type assertion
// bad
function getLength(something: string | number): number {
return something.length;
}
// index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'.
// Property 'length' does not exist on type 'number'.
// bad
function getLength(something: string | number): number {
if ((<string>something).length) {
return (<string>something).length;
} else {
return something.toString().length;
}
}
// good
function getLength(something: string | number): number {
if (typeof something === 'string') {
return something.length;
} else {
return something.toString().length;
}
}
12. Interface declaration order
there are four kinds of daily use: read-only parameters first, required parameters second, optional parameters second, uncertain parameters last
interface iProps {
readonly x: number;
readonly y: number;
name: string;
age: number;
height?: number;
[propName: string]: any;
}
13. Ts useful tools generics
- Record uses this to declare the type of object structure
Used to define a javascript object. Key is a string, and value is of any type
const people:Record<string,any> = {
name: 'chengfeng',
age: 10
}
- Partial is used to make incoming properties optional.
interface iPeople {
title: string;
name: string;
}
const people: Partial<iPeople> = {
title: 'Delete inactive users',
};
The defined structure can be any of the interfaces iPeoplekey
The function of
- Readonly is to make the incoming property read-only
interface iPeople {
title: string;
name: string;
}
const people: Readonly<Todo> = {
title: 'todo list',
name: chenfeng;
};
The title name attribute is read-only
The function of
- Required is to make the passed property a required option
interface iPeople {
title?: string;
name?: string;
}
const people1: Props = { title: 'ts' }; // OK
const people22: Required<iPeople> = { title: 'ts' }; // Error: property 'name' missing
see more
14. Ts some useful little tips
- keyof
interface iPeople {
name: string;
age: number
}
type T = keyof iPeople // -> "name" | "age"
- in
type Keys = "a" | "b"
type Obj = {
[p in Keys]: any
} // -> { a: any, b: any }
15. Standardize other
- do not use var to declare variables
- variables that will not be modified are declared using const
- remove declared but unreferenced code
- prohibit using debug in code
- No available code blocks are allowed
16. Only when the initial state needs to be calculated from props, put the declaration of state in the constructor, otherwise use the static attribute to declare state, and generally do not pass prop to state
// bad
constructor (){
this.setState({ people: this.props.people })
}
// good
state: IState = {
people: {},
};
17. Render default
- adding non-null judgments can improve the robustness of the code. For example, some values returned by the backend may not exist and should be given a default value.
// bad
render(){
{name}
}
// good
render(){
{!!name || '--'}
}
- there is another situation, that is, the backend is supposed to return an array to you, but the database cannot get the data, so the backend may return null to you, and then front-end null.length. So gg
// bad
const { list, totalCount } = await getPeopleList(keyword, page, pageSize);
list Could benullorundefined
list.lengthWill directly lead to front-end error reporting
this.setState({
status: STATUS.READY,
apps: list,
total: totalCount,
page: page,
});
// good
const { list, totalCount } = await getPeopleList(keyword, page, pageSize);
this.setState({
status: STATUS.READY,
apps: list || [],
total: totalCount || 0,
page: page,
});
18. Uncertain attributes, but in the end crazy use. Access properties that do not exist
for example, in some places, you are not sure what is in this variable, but you think it is crazy. The most obvious thing is that the backend returns an object to you. After the front end gets it, the judgment does not judge directly data.dataList.forEach ()
.
// bad
const data = await getPeopleList(keyword, page, pageSize);
data.dataList.forEach() // Just hang up
// good
const data = await getPeopleList(keyword, page, pageSize);
if (data && data.dataList && Array.isArray(data.dataList) {
data.dataList.forEach()
}
19. Data format conversion
- you can use the + sign to convert strings to integers
let maxPrice = +form.maxPrice.value;
let maxPrice = Number(form.maxPrice.value);
- convert to boolean value!
let mobile = !!ua.match(/iPhone|iPad|Android|iPod|Windows Phone/);
20. Judge whether the condition is true or false
in js, the following is false, other cases are true
- false
- null
- undefined
- 0
- ''(empty string)
- NaN
Comments