Skip to content

Commit 31d3cbc

Browse files
authored
Update typescript.md
1 parent df852eb commit 31d3cbc

1 file changed

Lines changed: 0 additions & 41 deletions

File tree

src/content/learn/typescript.md

Lines changed: 0 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,10 @@ TypeScript — папулярны спосаб дадаць тыпізацыю
1111

1212
<YouWillLearn>
1313

14-
<<<<<<< HEAD
1514
* [TypeScript з кампанентамі React](/learn/typescript#typescript-with-react-components)
1615
* [Прыклад тыпізацыі хукаў](/learn/typescript#example-hooks)
1716
* [Агульныя тыпы з `@types/react`](/learn/typescript/#useful-types)
1817
* [Іншыя рэсурсы для вывучэння](/learn/typescript/#further-learning)
19-
=======
20-
* [TypeScript with React Components](/learn/typescript#typescript-with-react-components)
21-
* [Examples of typing with Hooks](/learn/typescript#example-hooks)
22-
* [Common types from `@types/react`](/learn/typescript/#useful-types)
23-
* [Further learning locations](/learn/typescript/#further-learning)
24-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
2518

2619
</YouWillLearn>
2720

@@ -131,23 +124,13 @@ export default App = AppTSX;
131124

132125
## Прыклады хукаў {/*example-hooks*/}
133126

134-
<<<<<<< HEAD
135127
Апісанні тыпаў у `@types/react` уключае таксама і тыпізацыю ўбудаваных хукаў, таму вы можаце выкарыстоўваць іх у сваіх кампанентах без дадатковай налады. Яны пабудаваныя такім чынам, каб улічваць код, ужо напісаны ў кампаненце, такім чынам вы атрымаеце [аўтаматычна вызначаныя тыпы](https://www.typescriptlang.org/docs/handbook/type-inference.html) і ў большасці выпадкаў вам не давядзецца разбірацца з дробнай тыпізацыяй самастойна.
136128

137129
Але далей мы разгледзім некалькі прыкладаў, як тыпізаваць хукі.
138130

139131
### `useState` {/*typing-usestate*/}
140132

141133
[Хук `useState`](/reference/react/useState) будзе выкарыстоўваць значэнне, зададзенае пры ініцыалізацыі, для аўтаматычнага вызначэння тыпу. Напрыклад:
142-
=======
143-
The type definitions from `@types/react` include types for the built-in Hooks, so you can use them in your components without any additional setup. They are built to take into account the code you write in your component, so you will get [inferred types](https://www.typescriptlang.org/docs/handbook/type-inference.html) a lot of the time and ideally do not need to handle the minutiae of providing the types.
144-
145-
However, we can look at a few examples of how to provide types for Hooks.
146-
147-
### `useState` {/*typing-usestate*/}
148-
149-
The [`useState` Hook](/reference/react/useState) will re-use the value passed in as the initial state to determine what the type of the value should be. For example:
150-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
151134

152135
```ts
153136
// Тут будзе вызначаны тып boolean
@@ -183,11 +166,7 @@ const [requestState, setRequestState] = useState<RequestState>({ status: 'idle'
183166

184167
### `useReducer` {/*typing-usereducer*/}
185168

186-
<<<<<<< HEAD
187169
[Хук `useReducer`](/reference/react/useReducer) — больш скаладаны хук, які прымае функцыю рэд’юсара і першапачатковы стан. Аўтаматычна тып будзе вызначаны па тыпу значэння стану. Таксама вы можаце ўказаць тып стану пры выкліку `useReducer`, але звычайна лепей пакінуць першапачатковы стан:
188-
=======
189-
The [`useReducer` Hook](/reference/react/useReducer) is a more complex Hook that takes a reducer function and an initial state. The types for the reducer function are inferred from the initial state. You can optionally provide a type argument to the `useReducer` call to provide a type for the state, but it is often better to set the type on the initial state instead:
190-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
191170

192171
<Sandpack>
193172

@@ -263,11 +242,7 @@ export default function App() {
263242

264243
### `useContext` {/*typing-usecontext*/}
265244

266-
<<<<<<< HEAD
267245
[Хук `useContext`](/reference/react/useContext) — тэхніка для перадачы даных кампанентам уніз па дрэве без неабходнасці перадаваць пропсы цераз кампаненты. Выкарыстоўваецца шляхам стварэння кампанента-правайдара і хука для атрымання даных у даччыных кампанентах.
268-
=======
269-
The [`useContext` Hook](/reference/react/useContext) is a technique for passing data down the component tree without having to pass props through components. It is used by creating a provider component and often by creating a Hook to consume the value in a child component.
270-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
271246

272247
Аўтаматычна тып будзе вызначаны згодна з тыпам даных, што былі перададзеныя пры выкліку `createContext`:
273248

@@ -311,11 +286,7 @@ export default App = AppTSX;
311286

312287
Дадзеная тэхніка працуе калі маецца прадвызначанае значэнне, якое мае сэнс, але бываюць сітуацыі, калі такога няма. У такім выпадку разумна будзе скарыстацца `null` у якасці прадвызначанага значэння. Але каб сістэме тыпізацыі было зразумела, трэба відавочна ўказаць тып `ContextShape | null` для `createContext`.
313288

314-
<<<<<<< HEAD
315289
Разам з тым з’яўляецца патрэба выключаць `| null` пры атрыманні значэння. Мы раім дадаць у хук праверку, якая будзе падчас выканання правяраць наяўнасць значэння і выкідваць памылку пры яго адсутнасці:
316-
=======
317-
This causes the issue that you need to eliminate the `| null` in the type for context consumers. Our recommendation is to have the Hook do a runtime check for it's existence and throw an error when not present:
318-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
319290

320291
```js {5, 16-20}
321292
import { createContext, useContext, useState, useMemo } from 'react';
@@ -328,11 +299,7 @@ type ComplexObject = {
328299
// Кантэкст створаны з ужываннем `| null`, каб дакладна адлюстроўваць прадвызначанае значэнне
329300
const Context = createContext<ComplexObject | null>(null);
330301

331-
<<<<<<< HEAD
332302
// `| null` будзе выключаны пасля таго, як спрацуе хук.
333-
=======
334-
// The `| null` will be removed via the check in the Hook.
335-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
336303
const useGetComplexObject = () => {
337304
const object = useContext(Context);
338305
if (!object) { throw new Error("useGetComplexObject must be used within a Provider") }
@@ -362,11 +329,7 @@ function MyComponent() {
362329

363330
### `useMemo` {/*typing-usememo*/}
364331

365-
<<<<<<< HEAD
366332
[Хук `useMemo`](/reference/react/useMemo) дапамагае ствараць і паўторна атрымліваць доступ да запомненых вынікаў запуску функцыі. Функцыя будзе выконвацца наноў толькі ў выпадках, калі зменіцца залежнае значэнне, перададзенае другім параметрам. Вынік выкліку функцыі будзе аўтаматычна тыпізаваны адпаведна функцыі, што была перададзеная першым параметрам. Вы можаце тыпізаваць хук відавочна, перадаўшы яму тып.
367-
=======
368-
The [`useMemo`](/reference/react/useMemo) Hooks will create/re-access a memorized value from a function call, re-running the function only when dependencies passed as the 2nd parameter are changed. The result of calling the Hook is inferred from the return value from the function in the first parameter. You can be more explicit by providing a type argument to the Hook.
369-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
370333

371334
```ts
372335
// Тып visibleTodos вызначаны аўтаматычна з тыпу значэння, што вяртае функцыя filterTodos
@@ -376,11 +339,7 @@ const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
376339

377340
### `useCallback` {/*typing-usecallback*/}
378341

379-
<<<<<<< HEAD
380342
[Хук `useCallback`](/reference/react/useCallback) забяспечвае стабільную спасылку на функцыю пакуль залежнасці, перададзеныя другім параметрам, не змяняюцца. Як і `useMemo`, тып функцыі вызначаецца па тыпе функцыі, што перададзеная першым параметрам, але болей відавочна ўказаць тып можна перадаўшы яго ў хук.
381-
=======
382-
The [`useCallback`](/reference/react/useCallback) provide a stable reference to a function as long as the dependencies passed into the second parameter are the same. Like `useMemo`, the function's type is inferred from the return value of the function in the first parameter, and you can be more explicit by providing a type argument to the Hook.
383-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
384343

385344

386345
```ts

0 commit comments

Comments
 (0)