Não muito tempo atrás, eu desenterrei um repositório de desafios de tipo nos espaços abertos do GitHub . Tenho um blog inteiro onde resolvo problemas a partir daí, mas hoje vou tentar mostrar não só a implementação Get
, mas também demonstrar problemas comuns, mostrar melhorias e uso na produção.
Se você quiser se familiarizar com os conceitos do TypeScript exigidos neste artigo antes de ler, pule para o final.
Além disso, este artigo é uma tradução de um artigo que escrevi em inglês. Se estiver interessado, vá em frente .
1. Implementação básica
, ( )
?
1.1.
, JavaScript:
, keys.reduce
, . JavaScript split
. TypeScript - .
TypeScript 4.1, Template Literal types. . Path
:
. , ( ). Playground. :
. Playground.
1.2. Reducer
, , - keys.reduce
. , GetWithArray
, K
:
K extends [infer Key, ...infer Rest]
,
Key extends keyof O
O[Key]
( Playground). , . :
1.3.
, : Playground. , .
2.
production, , . ?
, null
undefined
.
: Playground. , TypeScript .
. - :
, undefined
or null
. .
2.1. undefined, null
3 :
, undefined
/ null
union type, , . "" .
, , Playground
2.2. reducer
GetWithArray
:
,
undefined
/null
, (
undefined
)
, ( Playground).
3.
:
JavaScript :
, string
number
, Path
:
3.1. Reducer
, keys.reduce
. TypeScript GetWithArray
. , GetWithArray
.
. A
O
:
Playground, :
string
:
'1' extends keyof string[]
,never
.
readonly
(
[0, 1, 2]
)never
undefined
:
.
3.2. T | undefined
T | undefined
( , ), T
:
A extends readonly (infer T)[]
, .. ( readonly
) .
, . Playground.
3.3.
, , ( undefined
)
, , extends
( ExtendsTable
) , :
4 :
[0]
number[]
readonly number[]
any[]
, , :
|
|
|
|
|
|
|
✅ |
✅ |
✅ |
✅ |
|
❌ |
✅ |
✅ |
✅ |
|
❌ |
❌ |
✅ |
❌ |
|
❌ |
✅ |
✅ |
✅ |
✅ , , . :
[0] extends [0]
number[] extends readonly number[]
, ❌, , . :
number[] extends [0]
readonly number[] extends number[]
any[]
: [0]
❌, () – ✅.
, !
any[] extends A
GetWithArray
:
any[] extends A
T | undefined
, ,
,
undefined
, Playground.
4.
:
:
: ExtractFromObject
ExtractFromArray
, , , :
ExtractFromObject
–O extends Record<PropertyKey, unknown>
. ,O
ExtractFromArray
:A extends readonly any[]
GetWithArray
:
. Playground.
5. JavaScript
JavaScript:
lodash
, get
. common/object.d.ts @types/lodash
, . get
any
: typescript-lodash-types
reduce
for
( for-of
), , undefined
null
:
get
, . :
Get
,
- (, )
. Get
:
Summary
TypeScript:
TypeScript 1.3, (Variadic Tuple Types) 4.0, spread
(Conditional types) TypeScript 2.8
infer
, TypeScript 2.8
(Recursive conditional types) TypeScript 4.1
(Template Literal types) TypeScript 4.1
(?) (Generic Constrains)
-
Obrigado a todos pela atenção. Se você tiver alguma sugestão, escreva nos comentários. Tenham todos uma boa noite e fim de semana.