Skip to content

Unsafe type assertions #176

@KaelWD

Description

@KaelWD

as unknown as T

https://github.com/search?q=repo%3Avuetifyjs%2F0%20%22as%20unknown%20as%22&type=code

This is effectively the same as as any as T and completely bypasses type checking for the assignment. Most of these seem to be used because of:

Generic parameters used only as shorthand

Example:

function createBreakpointsFallback<
E extends BreakpointsContext = BreakpointsContext,
> (options: BreakpointsOptions = {}): E {
if (options.ssr) return createBreakpoints(options)
const defaults = createDefaultBreakpoints()
return {
breakpoints: defaults.breakpoints,
mobileBreakpoint: defaults.mobileBreakpoint,
name: readonly(shallowRef<BreakpointName>('xs')),
width: readonly(shallowRef(0)),
height: readonly(shallowRef(0)),
isMobile: readonly(shallowRef(true)),
xs: readonly(shallowRef(true)),
sm: readonly(shallowRef(false)),
md: readonly(shallowRef(false)),
lg: readonly(shallowRef(false)),
xl: readonly(shallowRef(false)),
xxl: readonly(shallowRef(false)),
smAndUp: readonly(shallowRef(false)),
mdAndUp: readonly(shallowRef(false)),
lgAndUp: readonly(shallowRef(false)),
xlAndUp: readonly(shallowRef(false)),
smAndDown: readonly(shallowRef(true)),
mdAndDown: readonly(shallowRef(true)),
lgAndDown: readonly(shallowRef(true)),
xlAndDown: readonly(shallowRef(true)),
ssr: false,
update: () => {},
} as E
}

This is never called as createBreakpointsFallback<SomethingElse> so could be

function createBreakpointsFallback (options: BreakpointsOptions = {}): BreakpointsContext

The generic return type is also a lie, createBreakpointsFallback<BreakpointsContext & { foo: string }>() does not actually return an object with foo which would result in a runtime error if you tried to access it.

Lots more examples of this like:

export function createLocale<
Z extends LocaleTicketInput = LocaleTicketInput,
E extends LocaleTicket<Z> = LocaleTicket<Z>,
R extends LocaleContext<Z, E> = LocaleContext<Z, E>,
> (_options: LocaleOptions = {}): R {
const { adapter: externalAdapter, messages = {}, fallback: fallbackLocale, ...options } = _options
const tokens = createTokens(messages)
const registry = createSingle<Z, E>(options)
for (const id in messages) {
registry.register({ id } as unknown as Partial<Z>)

register({ id }) should satisfy Partial<LocaleTicketInput> but because createSingle uses the generic parameter Z typescript can't know if createLocale might be called with a wider type that has more required properties.
Again none of these generic parameters seem to be used, replacing Z E and R with LocaleTicketInput LocaleTicket and LocaleContext allows all the type assertions to be removed.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions