Last active
February 9, 2022 18:48
-
-
Save zachhardesty7/737d914974c9ae26935a5c3fcfdc0289 to your computer and use it in GitHub Desktop.
unsound TS function type annotations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// copyright 2022 Zach Hardesty | |
// want to check this out in the TypeScript playground? | |
// visit the following link to automatically see the latest version! | |
// https://www.typescriptlang.org/play?jsx=0#gist/737d914974c9ae26935a5c3fcfdc0289 | |
// TODO: write functions that mimic React for better example | |
// see the comment toward the bottom for the issue | |
type SetStateAction<S> = S | ((prevState: S) => S) | |
type Dispatch<A> = (value: A) => void | |
// function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>]; | |
type IOne = { | |
a: number | |
} | |
type ITwo = { | |
a: number | |
b: string | undefined | |
} | |
type IThree = { | |
a: number | |
b: string | |
} | |
const genericFunction = <T>(input: T): T => { | |
return input | |
} | |
const DEFAULT_1: IOne = { a: 1 } | |
const DEFAULT_2: ITwo = { a: 2, b: undefined } | |
// removing `<IOne>` will show the correct error | |
const out = genericFunction<IOne>(DEFAULT_2) | |
const OBJ_3: IThree = { a: 3, b: "obj 3" } | |
const newOut: IThree = { ...OBJ_3, ...out } | |
console.log("out", out) | |
console.log("new out", newOut) | |
newOut.b.substring(1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment