I have this:
export interface HavenData {
timeoutAmount: number;
throwSync?: boolean;
timeoutThrow: boolean;
promiseThrow: boolean;
}
const qs = {timeout: Math.ceil(30 * Math.random())} as Partial<HavenData>;
shouldn't that be an error since timeout is not a member of the HavenData interface? I am not seeing a problem in my IDE.
Type assertions are meant to be as lenient as possible, so excess property errors won't occur; that means you're almost always able to use a type assertion with something that's all-optional.
I feel like @RyanCavanaugh might have opinions about this though.
I was thinking that this was like "F you, just do what I want":
const qs = <Partial<HavenData>>{timeout: Math.ceil(30 * Math.random())};
but that this was more like "please complain if the cast will likely not work":
const qs = {timeout: Math.ceil(30 * Math.random())} as Partial<HavenData>;
Nope, the two are semantically equivalent; x as Foo was introduced because of parsing problems related to JSX, but it works the same in the type system.
If you want the compiler to complain, I'd go for a type annotation instead of an assertion:
const qs: Partial<HavenData> = { timeout: Math.ceil(30 * Math.random()) };
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Type '{ timeout: number; }' is not assignable to type 'Partial<HavenData>'.
// Object literal may only specify known properties, and 'timeout' does not exist
// in type 'Partial<HavenData>'.
I'm vaguely surprised this isn't an error due to Partial<T> being a weak type. Did we carve out something specific that makes this work?
@DanielRosenwasser What is the proposal here?
@DanielRosenwasser ping on the above question
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
Most helpful comment
If you want the compiler to complain, I'd go for a type annotation instead of an assertion: