Skip to content

Instantly share code, notes, and snippets.

@knowbody
Created July 16, 2019 08:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knowbody/b524f51941aa5b16bd77c73e7df0f797 to your computer and use it in GitHub Desktop.
Save knowbody/b524f51941aa5b16bd77c73e7df0f797 to your computer and use it in GitHub Desktop.
type Message = {
id: number;
body: string;
}
type State = {
messages: Message[]
}
const messages: Message[] = [
{
id: 1,
body: 'Hi!',
createdAt: '2019-07-16T07:21:40.878Z' // this will throw an error as I would expect as the `createdAt` is not defined in the `Message` type
},
{
id: 2,
body: 'Hey! 💪🏻🤩'
}
]
class MyComponent extends React.Component<{}, State> {
constructor(props) {
super(props);
this.state = {
messages
}
}
addMessage = (text: string) => {
this.setState(state => ({
messages: [
...state.messages,
{
id: 20,
body: text,
createdAt: '' // I would expect the same error being thrown here, why there is no error?? and why the `messages` (line 34) type gets extended with the object literal that icludes `createdAt`
}
]
}))
}
render() {
return null
}
}
@benedyktdryl
Copy link

// Also, the ` | S` allows intellisense to not be dumbisense
        setState<K extends keyof S>(
            state: ((prevState: Readonly<S>, props: Readonly<P>) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null),
            callback?: () => void
        ): void;
  • (Pick<S, K> | S
  • "the | S allows intellisense to not be dumbisense"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment