FAQs and Tips for Beginners in React + Typescript
Create a Union type constant Key
const NAME = { HOGE: "hoge", FUGA: "fuga" } as const; keyof typeof NAME // => "HOGE" | "FUGA"
Create a union type of constant value
typeof NAME[keyof typeof NAME] // => "hoge" | "fuga"
Depressed
const { hoge, piyo } = as { hoge: string; piyo: string; };
Force downward
There is danger, but...
const { hoge, piyo } = as unknown as { hoge: number; piyo: number; };
Material-Extend UI Type
Basically it is provided by the naming convention "Component Name + Props", so use it.
type ExtendsProps = TextFieldProps & { hoge: number; };
Use Material-UI property types
Types of TextFieldTextFieldProps
Can be inherited, but if you want to use its name attribute
type Props = { name: TextFieldProps["name"]; };
Common comment prefix annotation annotation annotation (FIXME, TODO, etc.)
In VSCode, you can highlight and view it in the list by setting a plug-in such as todo-tree.
Comment | significance |
---|---|
FIXME: | Flawed code. I have a strong desire to solve it. |
TODO: | what to do. Weaker than FIXME. Features to be fixed. |
NOTE: | Writing when emphasizing the intention of realization and why it is written like this. |
HACK: | I want to refactor. |
REVIEW: | Need to review or view. |
WARNING: | Beware. |
What is fake
False, undefined, null, NaN, 0, etc. are true/false values, and are false.
Please refer to MDN for everything.
// false, undefined, null, NaN, 0などのとははのエどのはのエどぼログをhairをhairるif (!hoge) { ("hoge がありません"); } (hoge);
Suddenly ||What is this?
A common conditional branchOR
。
When the left side isFalsy
When , use continuous calculation of the properties of the right expression.
(The following code"HOGE"
yesTruthy
)
That is, if hoge is Falsy,"HOGE"
Can be output to the screen.
const HogeComponent = ({ hoge }) => { return <div>{hoge || "HOGE"}</div>; };
const a1 = false || "hoge"; // f || t returns "hoge" const a2 = "hoge" || false; // t || f returns "hoge"
What is sudden&&?
A common conditional branchAND
。
When the left side isTruthy
When , use continuous calculation of the properties of the right expression.
That is, if loading is Truthy (the page is loading), the Loading component intends to print it to the screen.
const HogeComponent = ({ loading, hoge }) => { return ( <> {loading && <Loading />} <Typography>{hoge}</Typography> </> ); };
? and? ? What is it
Optional chain?.
If the reference is null (null or undefined), the expression is shortened and returns undefined instead of an error.
Empty merge operator ??
If the left side is empty, the value on the right side is returned, otherwise the value on the left side is returned.
- If the user is not defined, return undefined
- "hoge" is displayed when the attribute hoge contained in user is null or undefined
const piyoList = userList?.map((user) => ({ hoge: user?.hoge ?? "hoge", fuga: user?.fuga ?? "fuga", piyo: user?.piyo ?? "piyo", }));
How should I use ?? and || correctly?
The || operator is often confused because it contains the judgment of the ?? operator.
undefined || If you only want to make limited judgments when null, the advantage of using the ?? operator is that others are more likely to understand the intention when reading the code, and depending on the situation, unintentional behavior may occur. It is conceivable.
Inconvenient examples
For example, when passing the number 0 as a parameter, || is inappropriate. (Because the Falsey value contains 0)
Suppose there is a component that can specify any width as shown below.
const WidthComponent = ({ width }) => { return <div style={{ minWidth: width || "400px" }}>Bannerをきめる</div> };
If the width is specified to 0 when this component is called, 400px is always applied. This is because 0 is Falsy and moved to the evaluation to the right.
I want to use optional chains in a function
This can be achieved by writing functionName ?. ().
Of course, multiple optional chains can also be used together.
const productName = product?.getName?.();
By using it, the following redundant description can be reduced.
const productName = product?.getName ? () : undefined;
I want to use optional chains in an array
const product = products?.[0]
It is possible by description.
If you want to have an optional chain after the array index, please[]
Write later?
const user = userList?.[3]?.hoge ?? "HOGE"
Based on the above test
const userList = [ {hoge:"hoge1",piyo:"piyo1"}, {hoge:"hoge2",piyo:"piyo2"}, {hoge:"hoge3",piyo:"piyo3"}, ] const user = userList?.[3]?.hoge ?? "HOGE" (user); // whatがoutるかな?
The theory that it is best to use template text for string concatenation
While it depends on the site, it is basically better to use template literals for string concatenation.
const mergeString = (hoge: string, fuga: string, piyo: string) => `${hoge}_${fuga}_${piyo}`;
The above arrow function is written without return
Arrow functions can be written so that curly braces can be omitted and no return is required.
I used to generate a suitable key.
If the scope of the above function is appropriate, it will look like this.
const mergeString = (hoge: string, fuga: string, piyo: string) => { return `${hoge}_${fuga}_${piyo}`; };
Merge arrays
const hoge = [1, 2, 3]; const fuga = [4, 5, 6]; const piyo = [...hoge, ...fuga]; // => [1,2,3,4,5,6]
Difference update object
const defaultValue = { hoge: "hoge", fuga: "fuga", piyo: "piyo", }; const inputValue = { hoge: "hogehoge", fuga: "fugafuga", }; const result = { ...defaultValue, ...inputValue }; // => {hoge: "hogehoge", fuga: "fugafuga", piyo: "piyo"}
Pass parameters to the component together
type HogeProps = { hoge: string; piyo: string; }; export const Hoge: <HogeProps> = (props) => { return ( <> <ChildComponent {...props} /> </> ); };
Split allocation can be done with another name
Used when calling Hooks, etc., its return type is fixed in components of the same hierarchy.
This occurs frequently when using FetchQuery from the apollo client. should.
type Response = { loading:boolean; data: unknown; } const getResponse = ():Response => ({ loading: true; data : { hoge: "hoge"; fuga: "fuga"; } }) const {data, loading} = getResponse(); // Usually partitioning// Aliased partition substitutionconst {data: data2, loading: loading2} = getResponse()
Split assignment can also handle nesting
You can also split and allocate nested people!
type APIResponse = { code: string; data: { hoge: string; fuga?: string; piyo?: string; }[]; }; const { code, data: [{ hoge, fuga, piyo }], } = res; // res は APIResponsetypeとする
at the end
If you have any suggestions or it's a pointless thing, feel free to comment.
This is the article about FAQs and tips for beginners in the React + Typescript field. For more relevant FAQs, please search for my previous articles or continue browsing the related articles below. I hope you can support me in the future!