Skip to content

Commit dce4369

Browse files
Merge pull request #25 from dantecalderon/up-to-date-advanced
Up to date ADVANCED and move Linting to README
2 parents 91c63c2 + 0e53b0b commit dce4369

File tree

2 files changed

+230
-103
lines changed

2 files changed

+230
-103
lines changed

AVANZADO.md

+129-103
Original file line numberDiff line numberDiff line change
@@ -71,20 +71,22 @@ La mejor herramienta para crear bibliotecas React + TS en este momento es [`tsdx
7171
- [TypeScript 3.2](#typescript-32)
7272
- [TypeScript 3.3](#typescript-33)
7373
- [TypeScript 3.4](#typescript-34)
74+
- [TypeScript 3.5](#typescript-35)
75+
- [TypeScript 3.6](#typescript-36)
76+
- [TypeScript 3.7](#typescript-37)
7477
- [Sección 3: Misceláneas](#sección-3-Misceláneas)
75-
7678
- [Escribir bibliotecas de TypeScript en lugar de aplicaciones](#escribir-bibliotecas-de-typeScript-en-lugar-de-aplicaciones)
7779
- [Componentes Comentados](#componentes-comentados)
7880
- [Componentes Namespaced](#componentes-namespaced)
7981
- [Desarrollo de Sistemas de Diseño](#desarrollo-de-sistemas-de-diseño)
8082
- [Migrando desde Flow](#migrando-desde-flow)
8183
- [Prettier](#prettier)
84+
- [Testing](#testing)
8285
- [Linting](#linting)
8386
- [Trabajar con bibliotecas que no son de TypeScript (escribe tu propio index.d.ts)](#trabajar-con-bibliotecas-que-no-son-de-typeScript-escribe-tu-propio-indexdts)
8487
- [Sección 4: @types/react y @types/react-dom APIs](#sección-4-typesreact-y-typesreact-dom-apis)
8588
- [Agregando atributos no estandarizados](#agregando-atributos-no-estandarizados)
8689
- [@types/react-dom](#types-react-dom)
87-
8890
</details>
8991

9092
# Sección 0: Tipos de utilidad
@@ -699,7 +701,8 @@ Como puede ver en el ejemplo anterior de Omitir, también puede escribir una ló
699701

700702
_(Contribuido por [@ferdaber](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/63))_
701703

702-
Hay muchos lugares donde desea reutilizar algunas piesas de props debido a _props drilling_, para que pueda exportar el tipo de accesorios como parte del módulo o extraerlos (de cualquier manera funciona).
704+
Hay muchos lugares donde desea reutilizar algunas piesas de props debido a _props drilling_,
705+
para que pueda exportar el tipo de accesorios como parte del módulo o extraerlos (de cualquier manera funciona).
703706

704707
La ventaja de extraer los tipos de props es que no necesitas exportar todo. Y el componente fuente se propagará a todos los componentes consumidores.
705708

@@ -756,8 +759,7 @@ class DateIsInFutureError extends RangeError {}
756759
function parse(date: string) {
757760
if (!isValid(date))
758761
throw new InvalidDateFormatError("no es un formato de fecha válido");
759-
if (isInFuture(date))
760-
throw new DateIsInFutureError("la fecha es en el futuro");
762+
if (isInFuture(date)) throw new DateIsInFutureError("la fecha es en el futuro");
761763
// ...
762764
}
763765

@@ -784,8 +786,7 @@ function parse(
784786
): Date | InvalidDateFormatError | DateIsInFutureError {
785787
if (!isValid(date))
786788
return new InvalidDateFormatError("no es un formato de fecha válido");
787-
if (isInFuture(date))
788-
return new DateIsInFutureError("la fecha es en el futuro");
789+
if (isInFuture(date)) return new DateIsInFutureError("la fecha es en el futuro");
789790
// ...
790791
}
791792

@@ -893,6 +894,22 @@ Ayuda a escribir / usar componentes genéricos:
893894
894895
Más información: https://github.com/basarat/typescript-book/blob/master/docs/jsx/react.md#react-jsx-tip-generic-components
895896
897+
## TypeScript 3.0
898+
899+
[[Notas de la versión](https://github.com/Microsoft/TypeScript/releases/tag/v3.0.1) | [Publicación del blog](https://blogs.msdn.microsoft.com/typescript/2018/07/30/announcing-typescript-3-0/)]
900+
901+
1. Parametros rest con tipo para escribir argumentos de longitud variable:
902+
903+
```ts
904+
// `rest` acepta cualquier numero de strings - incluso ninguno!
905+
function foo(...rest: string[]) {
906+
// ...
907+
}
908+
909+
foo("hello"); // funciona
910+
foo("hello", "world"); // también funciona
911+
```
912+
896913
2. Soporte para `propTypes` y`static defaultProps` en JSX usando `LibraryManagedAttributes`:
897914
898915
```tsx
@@ -1070,10 +1087,106 @@ const GenericComponent2 = myHoc(GenericComponent);
10701087
10711088
Consulte también [Notas de la actualización de Google a 3.5](https://github.com/microsoft/TypeScript/issues/33272)
10721089
1073-
## TypeScript Roadmap
1090+
## TypeScript 3.6
1091+
1092+
[[Notas de la versión](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-6.html) | [Publicación del blog](https://devblogs.microsoft.com/typescript/announcing-typescript-3-6/)]
1093+
1094+
Nada es particularmente específico de React, pero [el playground](https://github.com/agentcooper/typescript-play) recibió una actualización y [Las clases Ambientales y Funciones pueden fusionarse](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-6.html#ambient-classes-and-functions-can-merge)
1095+
1096+
## TypeScript 3.7
1097+
1098+
[[Notas de la versión](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html) | [Publicación del blog](https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/)]
1099+
1100+
1. Optional Chaining
1101+
1102+
```ts
1103+
let x = foo?.bar.baz();
1104+
1105+
// es equivalente a
1106+
1107+
let x = foo === null || foo === undefined ? undefined : foo.bar.baz();
1108+
1109+
// Optional Element access
1110+
function tryGetFirstElement<T>(arr?: T[]) {
1111+
return arr?.[0];
1112+
}
1113+
1114+
// Llamada opcional
1115+
async function makeRequest(url: string, log?: (msg: string) => void) {
1116+
log?.(`Request started at ${new Date().toISOString()}`);
1117+
const result = (await fetch(url)).json();
1118+
log?.(`Request finished at at ${new Date().toISOString()}`);
1119+
return result;
1120+
}
1121+
```
1122+
1123+
2. Fusión nula
1124+
1125+
```ts
1126+
let x = foo ?? bar();
1127+
1128+
// es equivalente a
1129+
1130+
let x = foo !== null && foo !== undefined ? foo : bar();
1131+
```
1132+
1133+
**POR LO GENERAL DEBES USAR `??` SIEMPRE QUE USAS NORMALMENTE `||`** a menos que realmente te refieras a falsedad:
1134+
1135+
```tsx
1136+
function ShowNumber({ value }: { value: number }) {
1137+
let _value = value || 0.5; // reemplazará 0 con 0.5 incluso si el usuario se refiere a 0
1138+
// etc...
1139+
}
1140+
```
1141+
1142+
3. Funciones de Aserción
1143+
1144+
```tsx
1145+
function assert(condition: any, msg?: string): asserts condition {
1146+
if (!condition) {
1147+
throw new AssertionError(msg);
1148+
}
1149+
}
1150+
function yell(str) {
1151+
assert(typeof str === "string");
1152+
1153+
return str.toUppercase();
1154+
// ~~~~~~~~~~~
1155+
// error: La propiedad 'toUppercase' no existe en el tipo 'string'.
1156+
// Querías decir 'toUpperCase'?
1157+
}
1158+
```
1159+
1160+
También puede hacer assert sin una función personalizada
1161+
You can also assert without a custom function:
1162+
1163+
```tsx
1164+
function assertIsString(val: any): asserts val is string {
1165+
if (typeof val !== "string") {
1166+
throw new AssertionError("Not a string!");
1167+
}
1168+
}
1169+
function yell(str: any) {
1170+
assertIsString(str);
1171+
1172+
// Ahora Typescript sabe que 'str' es de tipo 'string'
1173+
return str.toUppercase();
1174+
// ~~~~~~~~~~~
1175+
// error: La propiedad 'toUppercase' no existe el tipo 'string'.
1176+
// Querías decir 'toUpperCase'?
1177+
}
1178+
```
1179+
1180+
4. `ts-nocheck`
1181+
1182+
Ahora puedes añadir `// @ts-nocheck` a la parte superior de los archivos Typescript! bueno para las migraciones.
1183+
1184+
## TypeScript Roadmap y Especificaciones
10741185

10751186
https://github.com/Microsoft/TypeScript/wiki/Roadmap
10761187

1188+
¿Sabía también que puede leer la especificación de TypeScript en línea? https://github.com/microsoft/TypeScript/blob/master/doc/spec.md
1189+
10771190
# Sección 3: Misceláneas
10781191

10791192
A veces, escribir React no se trata solo de React. Si bien no nos centramos en otras bibliotecas como Redux (ver más abajo para obtener más información al respecto), aquí hay algunos consejos sobre otras preocupaciones comunes al hacer aplicaciones con React + TypeScript.
@@ -1216,105 +1329,18 @@ yarn add -D prettier husky lint-staged
12161329
}
12171330
```
12181331

1219-
Esto está configurado para ti en [tsdx](https://github.com/palmerhq/tsdx/pull/45/files).
1220-
1221-
## Linting
1222-
1223-
> ⚠️ Nota que [TSLint ahora está en mantenimiento y deberías intentar usar ESLint en su lugar](https://medium.com/palantir/tslint-in-2019-1a144c2317a9). Si está interesado en los consejos de TSLint, consulte este PR desde [@azdanov](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/pull/14). El resto de esta sección solo se centra en ESLint.
1224-
1225-
> ⚠️ Este es un tema en evolución. `typescript-eslint-parser` ya no se mantiene y [el trabajo ha comenzado recientemente sobre`typescript-eslint` en la comunidad ESLint](https://eslint.org/blog/2019/01/future-typescript-eslint) para lleve ESLint con TSLint.
1226-
1227-
Siga los documentos de TypeScript + ESLint en https://github.com/typescript-eslint/typescript-eslint:
1228-
1229-
```
1230-
yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint
1231-
```
1232-
1233-
agregue un script `lint` a su`package.json`:
1234-
1235-
```json
1236-
"scripts": {
1237-
"lint": "eslint 'src/**/*.ts'"
1238-
},
1239-
```
1240-
1241-
y en `.eslintrc.json` adecuado:
1332+
Integrar esto con ESlint puede ser un problema. Todavía no hemos escrito mucho sobre esto, por favor contribuya si tiene una opinión firme. [Aquí hay un gist útil.](https://gist.github.com/JirkaVebr/519c7597517e4ba756d5b89e7cb4cc0e)
12421333

1243-
```json
1244-
{
1245-
"env": {
1246-
"es6": true,
1247-
"node": true,
1248-
"jest": true
1249-
},
1250-
"extends": "eslint:recommended",
1251-
"parser": "@typescript-eslint/parser",
1252-
"plugins": ["@typescript-eslint"],
1253-
"parserOptions": {
1254-
"ecmaVersion": 2017,
1255-
"sourceType": "module"
1256-
},
1257-
"rules": {
1258-
"indent": ["error", 2],
1259-
"linebreak-style": ["error", "unix"],
1260-
"quotes": ["error", "single"],
1261-
"no-console": "warn",
1262-
"no-unused-vars": "off",
1263-
"@typescript-eslint/no-unused-vars": [
1264-
"error",
1265-
{ "vars": "all", "args": "after-used", "ignoreRestSiblings": false }
1266-
],
1267-
"no-empty": "warn"
1268-
}
1269-
}
1270-
```
1271-
1272-
Esto está tomado de [el `tsdx` PR](https://github.com/palmerhq/tsdx/pull/70/files) que es para **bibliotecas**.
1334+
Esto está configurado para ti en [tsdx](https://github.com/palmerhq/tsdx/pull/45/files).
12731335

1274-
Más opciones de `.eslintrc.json` se pueden desear para **aplicaciones**:
1336+
## Testing
12751337

1276-
```json
1277-
{
1278-
"extends": [
1279-
"airbnb",
1280-
"prettier",
1281-
"prettier/react",
1282-
"plugin:prettier/recommended",
1283-
"plugin:jest/recommended",
1284-
"plugin:unicorn/recommended"
1285-
],
1286-
"plugins": ["prettier", "jest", "unicorn"],
1287-
"parserOptions": {
1288-
"sourceType": "module",
1289-
"ecmaFeatures": {
1290-
"jsx": true
1291-
}
1292-
},
1293-
"env": {
1294-
"es6": true,
1295-
"browser": true,
1296-
"jest": true
1297-
},
1298-
"settings": {
1299-
"import/resolver": {
1300-
"node": {
1301-
"extensions": [".js", ".jsx", ".ts", ".tsx"]
1302-
}
1303-
}
1304-
},
1305-
"overrides": [
1306-
{
1307-
"files": ["**/*.ts", "**/*.tsx"],
1308-
"parser": "typescript-eslint-parser",
1309-
"rules": {
1310-
"no-undef": "off"
1311-
}
1312-
}
1313-
]
1314-
}
1315-
```
1338+
¡Sí, puedes probar tus tipos! No debe usarlo para TODO, pero puede ayudar a prevenir regresiones:
13161339

1317-
Puede leer una [guía de configuración más completa de TypeScript + ESLint aquí](https://blog.matterhorn.dev/posts/learn-typescript-linting-part-1/) de Matterhorn, en particular consulte https://github.com/MatterhornDev/learn-typescript-linting.
1340+
- https://github.com/azz/jest-runner-tsc
1341+
- https://github.com/SamVerschueren/tsd
1342+
- https://github.com/ikatyang/dts-jest ([Demo](https://codesandbox.io/s/dts-test-frozen-public-demo-iyorn))
1343+
- https://github.com/microsoft/dtslint ([Intro to dtslint](https://www.youtube.com/watch?v=nygcFEwOG8w&feature=share)
13181344

13191345
## Trabajar con bibliotecas que no son de TypeScript (escribe tu propio index.d.ts)
13201346

0 commit comments

Comments
 (0)