Skip to content

Commit

Permalink
fix(runtime-core): fix null type in required + multi-type prop declar…
Browse files Browse the repository at this point in the history
…ations

fix #4146 (in combination with #4147)
  • Loading branch information
yyx990803 committed Jul 19, 2021
1 parent cac6ab5 commit bbf6ca9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
17 changes: 17 additions & 0 deletions packages/runtime-core/__tests__/componentProps.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -556,4 +556,21 @@ describe('component props', () => {
await nextTick()
expect(serializeInner(root)).toBe(`foo`)
})

test('support null in required + multiple-type declarations', () => {
const Comp = {
props: {
foo: { type: [Function, null], required: true }
},
render() {}
}
const root = nodeOps.createElement('div')
expect(() => {
render(h(Comp, { foo: () => {} }), root)
}).not.toThrow()

expect(() => {
render(h(Comp, { foo: null }), root)
}).not.toThrow()
})
})
6 changes: 4 additions & 2 deletions packages/runtime-core/src/componentProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ function validatePropName(key: string) {
// so that it works across vms / iframes.
function getType(ctor: Prop<any>): string {
const match = ctor && ctor.toString().match(/^\s*function (\w+)/)
return match ? match[1] : ''
return match ? match[1] : ctor === null ? 'null' : ''
}

function isSameType(a: Prop<any>, b: Prop<any>): boolean {
Expand Down Expand Up @@ -637,6 +637,8 @@ function assertType(value: unknown, type: PropConstructor): AssertionResult {
valid = isObject(value)
} else if (expectedType === 'Array') {
valid = isArray(value)
} else if (expectedType === 'null') {
valid = value === null
} else {
valid = value instanceof type
}
Expand All @@ -656,7 +658,7 @@ function getInvalidTypeMessage(
): string {
let message =
`Invalid prop: type check failed for prop "${name}".` +
` Expected ${expectedTypes.map(capitalize).join(', ')}`
` Expected ${expectedTypes.map(capitalize).join(' | ')}`
const expectedType = expectedTypes[0]
const receivedType = toRawType(value)
const expectedValue = styleValue(value, expectedType)
Expand Down

0 comments on commit bbf6ca9

Please sign in to comment.