Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

Introduction to the

A common problem with typescript development is that you need a valueof function, but typescript doesn’t provide a valueof function. How do you do that?

Reference since: stackoverflow.com/questions/4…

series

Type-as const for all values of a Typescript object

example

import { useSelector } from 'react-redux';
import { RootState } from 'reducer';

export const PERMISSIONS = {
    PERMISSION_A: 'permission_a'.PERMISSION_B: 'permission_b',}as const;

type TPermissions = typeof PERMISSIONS[keyof typeof PERMISSIONS];

export const usePermissions = (curPermission: TPermissions) = > {
    const permissions = useSelector(state= > (state as RootState).user.permissions);
    return permissions.indexOf(curPermission) > -1;
};
Copy the code

Analysis of the

As const and keyof Typeof syntax are used in this article to introduce as const

as const

As const is called a const type assertion. A const type assertion tells the compiler to infer the expression as the most specific type. If it is not used, the compiler uses the default type inference behavior, which may infer the expression as a more general type.

Note that const is a type assertion, not a cast. In typescript, const type assertions are completely removed from compiled JavaScript, so applications that use or don’t use as const make no difference at runtime.

So as const just gives the compiler a better understanding of the intent of the code and makes it more precise in distinguishing between correct and wrong code

Reference: stackoverflow.com/questions/6…

The above is all explained as const