TypeScript

Pros:

  • Useful for preventing me from pushing the quick hacks I'm trying to commit in JavaScript.

Cons:

  • Modules you depend on may not have typescript definitions
    • To avoid typing, you may have to go backwards const ... = require()
  • Definition hell

Versioning

Node
TypeScript Target
Support
6.17
es5
AWS Lambda Node v6.10 support
es6
8.10-9.11.2
es2016
8.10-9.11.2
es2017
AWS Lambda Node v8.10 support
10-nightly
es2018
AWS Lambda Node v10.x support
es2019
General Rules:
  • If you are targeting for web set target to es5
  • If you targeting for AWS Lambda, set your target to es2018
    • Node.js v10.x supports es2018
  • If you are targeting for local and using the latest node, go for es2019
    • I'm assuming you can target for esnext as well as it wouldn't make sense to write code that the latest Node.js could write...but I could be wrong

Compiler Options

Enable:
  • declaration: true when you want to share a Typescript code across modules
  • jsx: react when you want to share a React component across modules

Sharing between models

Enable in your compiler option:
  • declaration: true
  • jsx: react

Typing

function and object destructuring

1
function Render(props: {uri?: string}) {
Copied!
1
function toJSON(
2
value: any,
3
{ pretty }: { pretty: boolean }
4
) {
5
const indent = pretty ? 4 : 0;
6
return JSON.stringify(value, null, indent);
7
}
Copied!

Objects

1
interface LRUHashMap {
2
[value: number]: DoublyLinkedList;
3
}
4
5
class LRUHash {
6
private hash: LRUHashMap;
7
8
construct() {
9
this.hash = {};
10
}
11
}
Copied!

Enums cannot be keys

This fails:
1
const enum Key { ... }
2
const config: { [key: Key]: string } = {};
Copied!
Keys can only be string or number.
Use Map instead:
1
const enum Key { ... }
2
const config = new Map<Key, string>();
Copied!

React

children

1
interface Props {
2
children?: any;
3
}
Copied!

useRef

1
export default function UriField() {
2
const [uri, setURI] = useState<string | null>(null);
3
const inputRef = useRef<HTMLInputElement>(null);
4
const onClick = () => {
5
if (!inputRef ||
6
!inputRef.current) {
7
return;
8
}
9
10
setURI(inputRef.current.value);
11
}
12
13
return (
14
<>
15
<input ref={inputRef} type="text" />
16
<input onClick={onClick} type="submit" value="Submit"/>
17
</>
18
);
19
}
Copied!
Last modified 3yr ago