当前位置:网站首页>Type assertion in typescript
Type assertion in typescript
2022-07-26 21:28:00 【Chaos front end (wechat official account)】
TypeScript The type assertion of seems to be conceptually simple , But for just touching TypeScript Users of , May lack understanding of usage scenarios , I hope this article can help you understand type assertion better .
When you use a value , however TypeScript I don't know the specific type perhaps TypeScript When the type of record cannot meet the use requirements , You can use type assertions to explicitly specify the type you want to use .
grammar :
There are two ways to assert a type :
Use <>grammarUse askeyword
<> Hui He JSX Grammar conflict , In general use as .
Let's look at some examples of type assertions
1. For those obtained through tags DOM,TypeScript You can infer the type , But for other ways ,TypeScript It is impossible to infer , We can use type assertions to explicitly specify the element type .
const aEle = document.querySelector('a') // HTMLAnchorElement | null
const canvasEle = document.querySelector('#my_canvas') as HTMLCanvasElement
React.useEffect(() => {
if (props.autoFocus) {
const $this = ref.current as HTMLInputElement;
...
}
}, []);
AntD Example in :ActionButton.tsx
2. For empty object placeholders , It can be asserted as a specific type , To get the correct code hints and type inference
const [user, setUser] = useState<User | null>(null);
setUser(newUser);
const [user, setUser] = useState<User>({} as User);
setUser(newUser);
const Assertion
const Assertions tell the compiler to infer for an expression the narrowest or most specific type it can infer , Instead of generic types .
// point To become a readonly An array type , Modifying the contents of the array will prompt an error .
let point = [3, 4] as const; // readonly [3, 4]
point[0] = 1 // Error
Let's take a look at a code example :
function useDarkMode() {
const [mode, setMode] = React.useState<'dark' | 'light'>(() => {
// ...
return 'light'
})
...
return [mode, setMode] as const
}
const [mode, setMode] = useDarkMode() // Pseudo code ,hook It needs to be used in function components
Let's compare mode and setMode Use as const Subsequent differences :
In the use of const Before asserting ,mode and setMode The type is :
const mode: "dark" | "light" | React.Dispatch<React.SetStateAction<"dark" | "light">>
const setMode: "dark" | "light" | React.Dispatch<React.SetStateAction<"dark" | "light">>

call setMode when , It will give you an error , because 'dark' | 'light' Is not a callable type .

Use as const After the assertion ,mode and setMode The type is :
const mode: "dark" | "light"
const setMode: React.Dispatch<React.SetStateAction<"dark" | "light">>


When calling parameter transfer error , There will also be type error prompts .

You can see , For arrays , The type of each element is the joint type of the entire array element type
const arr = [1,'2']
// const arr: (string | number)[]
Use as const After the assertion , The array will become readonly Array and Each element has its own specific type , There is also a better error prompt .
Let's see another one rxjs Example in :fromEvent.ts
// These constants are used to create handler registry functions using array mapping below.
// These constants are used to create handler registry functions using the following array mapping
const nodeEventEmitterMethods = ['addListener', 'removeListener'] as const;
const eventTargetMethods = ['addEventListener', 'removeEventListener'] as const;
const jqueryMethods = ['on', 'off'] as const;
Use as const after , Type detection is more stringent :
readonly Array , Each element has its own literal type , Cannot adjust to other values , Eliminate the possibility of accidental modification When accessing array elements or deconstructing arrays , Because the array length is fixed , Avoid crossing borders , It's not easy to make mistakes
const Assertions and typeof Use it with :useSelection.tsx
String usage as const after , Variables have literal types ,typeof Operators can extract their literal types using .
export const SELECTION_ALL = 'SELECT_ALL' as const;
export const SELECTION_INVERT = 'SELECT_INVERT' as const;
export type INTERNAL_SELECTION_ITEM =
| SelectionItem
| typeof SELECTION_ALL
| typeof SELECTION_INVERT;
Avoid type checking
TypeScript Only type assertions are allowed for a more specific or less specific type , This rule can prevent some wrong cast :
const x = "hello" as number;
// Error: take 'string' Type conversion to 'number' The type may be an error , Because these two types do not fully overlap . If it's intentional , Please convert the expression to “unknown”.
Let's take another look at Antd Examples of use in : back-top
React.useEffect(() => {
bindScrollEvent();
return () => {
if (scrollEvent.current) {
scrollEvent.current.remove();
}
(handleScroll as any).cancel();
};
}, [props.target]);
handleScroll It's a function , But other documents have been added cancel attribute , Call... Directly here cancel Method , TypeScript It will give you an error , Can be asserted as any To avoid TypeScript Type check of
Double assertion
For the variable types that we have defined , If there is no overlap , It can be asserted as a broad type first (any、unknown), Then assert as a specific type .
// es default export should use const instead of let
const ExportTypography = (RefTypography as unknown) as React.FC<TypographyProps>;
Be careful : When using assertions , Make sure you know the type of current value , Avoid error . For types that can be narrowed , Try to use type narrowing rather than assertions .
边栏推荐
- 【HCIA安全】双向NAT
- Summary of 4 years of software testing experience and interviews with more than 20 companies after job hopping
- Error in render: “TypeError: data.slice is not a function“
- 自定义注解(一)
- :active vs :focus
- 修改excel默认编码
- JS click the picture to print the image
- LiveDatade的基本使用
- Devsecops, speed and security
- 【虚拟机数据恢复】意外断电导致XenServer虚拟机不可用的数据恢复
猜你喜欢

如何借助自动化工具落地DevOps|含低代码与DevOps应用实践

Apaas low code platform (I) | leave complexity to yourself and simplicity to users

Redis hash和string的区别

About: get the domain controller of the current client login

What are the characteristics of low code tools? The two development tracks of low code that can be seen by discerning people!
![[HCIA security] NAT network address translation](/img/10/3b4d011963e00229d73a7435ce8c4b.png)
[HCIA security] NAT network address translation
![[must read new] Keya valuation analysis of University of technology, heating energy-saving products](/img/e8/c3ac4e5f11db58031cb9249a4ba0f4.jpg)
[must read new] Keya valuation analysis of University of technology, heating energy-saving products

Practice of microservice in solving Library Download business problems

Registration conditions for information system project managers in the second half of 2022 (soft examination advanced)

Difference between redis hash and string
随机推荐
[download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng
[HCIA security] user authentication
MySQL -count: the difference between count (1), count (*), and count (column name)
Relevant contents about wireless communication
立即报名:7 月 29 日推荐系统峰会 2022
kubernetes之Deployment
(C语言)浅识#define
Line detection based on Hough transform (matlab)
DevSecOps,让速度和安全兼顾
Devsecops, speed and security
功能尝鲜 | 解密 Doris 复杂数据类型 ARRAY
HTTP cache browser cache that rabbits can understand
Mysql -count :count(1)、count(*)、count(列名)的区别
获取文本选择的方向
2022-7-26 the seventh group of abstractions and interfaces
How to use multiple languages in a project?
[hero planet July training leetcode problem solving daily] 26th and check the collection
idea中debug时如何进入指定的用户方法体中?
Show load indicator when loading iframe
In addition to "adding machines", in fact, your micro service can be optimized like this