Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(componentProps): clean up code and improve types #410

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 16 additions & 10 deletions packages/runtime-core/src/componentProps.ts
Expand Up @@ -19,24 +19,30 @@ import { Data, ComponentInternalInstance } from './component'

export type ComponentPropsOptions<P = Data> =
| ComponentObjectPropsOptions<P>
| string[]
| Extract<keyof P, string>[]

export type ComponentObjectPropsOptions<P = Data> = {
[K in keyof P]: Prop<P[K]> | null
}

export type Prop<T> = PropOptions<T> | PropType<T>

type DefaultFactory<T> = () => T | null | undefined

interface PropOptions<T = any> {
type?: PropType<T> | true | null
required?: boolean
default?: T | null | undefined | (() => T | null | undefined)
validator?(value: unknown): boolean
default?:
| DefaultFactory<T>
| null
| undefined
| (T extends Function ? never : T) // If type of prop is function, only allow factory function
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this makes sense. Actually it seems to break certain cases.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Which ones?

validator?(value: T): boolean
}

export type PropType<T> = PropConstructor<T> | PropConstructor<T>[]

type PropConstructor<T = any> = { new (...args: any[]): T & object } | { (): T }
type PropConstructor<T = any> = { new (...args: never[]): T & object } | { (): T }

type RequiredKeys<T, MakeDefaultRequired> = {
[K in keyof T]: T[K] extends
Expand Down Expand Up @@ -282,11 +288,6 @@ function getTypeIndex(
return -1
}

type AssertionResult = {
valid: boolean
expectedType: string
}

function validateProp(
name: string,
value: unknown,
Expand All @@ -300,7 +301,7 @@ function validateProp(
return
}
// missing but optional
if (value == null && !prop.required) {
if (value == null && !required) {
return
}
// type check
Expand Down Expand Up @@ -329,6 +330,11 @@ const isSimpleType = /*#__PURE__*/ makeMap(
'String,Number,Boolean,Function,Symbol'
)

type AssertionResult = {
valid: boolean
expectedType: string
}

function assertType(value: unknown, type: PropConstructor): AssertionResult {
let valid
const expectedType = getType(type)
Expand Down