Skip to content

Commit ecd20eb

Browse files
authored
Fix ContainerWithChildren to allow discriminating the node type by comparing its type property (#2049)
* Fix ContainerWithChildren to allow discriminating the node type by comparing its type property * add more description to the test * Revert version changes * move tests to test/types.ts
1 parent c181597 commit ecd20eb

File tree

2 files changed

+38
-4
lines changed

2 files changed

+38
-4
lines changed

lib/container.d.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,17 @@ import AtRule from './at-rule.js'
22
import Comment from './comment.js'
33
import Declaration from './declaration.js'
44
import Node, { ChildNode, ChildProps, NodeProps } from './node.js'
5+
import { Root } from './postcss.js'
56
import Rule from './rule.js'
67

78
declare namespace Container {
8-
export class ContainerWithChildren<
9-
Child extends Node = ChildNode
10-
> extends Container_<Child> {
9+
export type ContainerWithChildren<Child extends Node = ChildNode> = {
1110
nodes: Child[]
12-
}
11+
} & (
12+
| AtRule
13+
| Root
14+
| Rule
15+
)
1316

1417
export interface ValueOptions {
1518
/**

test/types.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import postcss, { Document, PluginCreator } from '../lib/postcss.js'
2+
import { RootRaws } from '../lib/root.js'
23

34
const plugin: PluginCreator<string> = prop => {
45
return {
@@ -30,4 +31,34 @@ function parseMarkdown(): Document {
3031
let doc = postcss().process('a{}', { parser: parseMarkdown }).root
3132
console.log(doc.toString())
3233

34+
function parentCanNarrowType(): never | void {
35+
let atRule = postcss.parse('@a{b{}}').first
36+
if (atRule?.type !== 'atrule') return
37+
let rule = atRule.first
38+
if (rule?.type !== 'rule') return
39+
let parent = rule.parent
40+
switch (parent?.type) {
41+
case undefined:
42+
console.log('ok')
43+
break
44+
case 'atrule':
45+
console.log(parent.params)
46+
break
47+
case 'root':
48+
{
49+
let raws: RootRaws = parent.raws
50+
console.log(raws)
51+
}
52+
break
53+
case 'rule':
54+
console.log(rule.selector)
55+
break
56+
default: {
57+
let exhaustiveCheck: never = parent
58+
return exhaustiveCheck
59+
}
60+
}
61+
}
62+
parentCanNarrowType()
63+
3364
export default plugin

0 commit comments

Comments
 (0)