Skip to content

Instantly share code, notes, and snippets.

@coolsoftwaretyler
Last active February 16, 2024 03:11
Show Gist options
  • Save coolsoftwaretyler/e05ba039a94ad0105cde26f20bf44b21 to your computer and use it in GitHub Desktop.
Save coolsoftwaretyler/e05ba039a94ad0105cde26f20bf44b21 to your computer and use it in GitHub Desktop.
Weird TS Test Failure
// These assertions don't work, from https://github.com/mobxjs/mobx-state-tree/blob/master/__tests__/core/type-system.test.ts. Fails with TS 4.3 and greater. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-3.html
test("maybe / optional type inference verification", () => {
const T = types.model({
a: types.string,
b: "test",
c: types.maybe(types.string),
d: types.maybeNull(types.string),
e: types.optional(types.string, "test")
})
interface ITC extends SnapshotIn<typeof T> {}
interface ITS extends SnapshotOut<typeof T> {}
assert(
_ as ITC, // TS error: Argument of type 'ITC' is not assignable to parameter of type '"❌ Unexpected or missing 'readonly' property"'.
_ as {
[$nonEmptyObject]?: any
a: string
b?: string
c?: string | undefined
d?: string | null
e?: string
}
)
assert(
_ as ITS, // Argument of type 'ITC' is not assignable to parameter of type '"❌ Unexpected or missing 'readonly' property"'.
_ as {
[$nonEmptyObject]?: any
a: string
b: string
c: string | undefined
d: string | null
e: string
}
)
})
// But if we do any kind of modification on them, like omitting a key that doesn't exist, it works
test("maybe / optional type inference verification", () => {
const T = types.model({
a: types.string,
b: "test",
c: types.maybe(types.string),
d: types.maybeNull(types.string),
e: types.optional(types.string, "test")
})
interface ITC extends SnapshotIn<typeof T> {}
interface ITS extends SnapshotOut<typeof T> {}
assert(
_ as Omit<ITC, "non-existent-property">,
_ as {
[$nonEmptyObject]?: any
a: string
b?: string
c?: string | undefined
d?: string | null
e?: string
}
)
assert(
_ as Omit<ITS, "non-existent-property">,
_ as {
[$nonEmptyObject]?: any
a: string
b: string
c: string | undefined
d: string | null
e: string
}
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment