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
General Rules:
If you are targeting for web set target to
es5If you targeting for AWS Lambda, set your target to
es2018Node.js v10.xsupportses2018
If you are targeting for local and using the latest node, go for
es2019I'm assuming you can target for
esnextas well as it wouldn't make sense to write code that the latest Node.js could write...but I could be wrong
Compiler Options
https://www.typescriptlang.org/docs/handbook/compiler-options.html
Enable:
declaration: truewhen you want to share a Typescript code across modulesjsx: reactwhen you want to share a React component across modules
Sharing between models
Enable in your compiler option:
declaration: truejsx: react
Typing
function and object destructuring
https://mariusschulz.com/blog/typing-destructured-object-parameters-in-typescript
function Render(props: {uri?: string}) {function toJSON(
value: any,
{ pretty }: { pretty: boolean }
) {
const indent = pretty ? 4 : 0;
return JSON.stringify(value, null, indent);
}Objects
interface LRUHashMap {
[value: number]: DoublyLinkedList;
}
class LRUHash {
private hash: LRUHashMap;
construct() {
this.hash = {};
}
}Enums cannot be keys
This fails:
const enum Key { ... }
const config: { [key: Key]: string } = {};Keys can only be string or number.
Use Map instead:
const enum Key { ... }
const config = new Map<Key, string>();React
https://github.com/sw-yx/react-typescript-cheatsheet
children
interface Props {
children?: any;
}Recommended https://github.com/Microsoft/TypeScript/issues/6471#issuecomment-171456118
useRef
export default function UriField() {
const [uri, setURI] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const onClick = () => {
if (!inputRef ||
!inputRef.current) {
return;
}
setURI(inputRef.current.value);
}
return (
<>
<input ref={inputRef} type="text" />
<input onClick={onClick} type="submit" value="Submit"/>
</>
);
}Last updated
Was this helpful?