简体   繁体   中英

Recursive type-declaration in Typescript

I've tried this every which way I can think of, and I did look at other similar posts regarding recursive types, but I haven't been able to create a type that works recursively for this case.

What I want is for this type to accept partial properties of CSSStyleDeclaration , and, for any properties not matching a property of CSSStyleDeclaration , I want it to map back to the type itself.

This seems to work only for the first level:

interface NestedCSSDeclarations {
    [name: string]: CSSDeclaration;
}

type CSSDeclaration = {
    [P in keyof CSSStyleDeclaration]?: CSSStyleDeclaration[P];
} & NestedCSSDeclarations

function css(obj: CSSDeclaration) {
    // ...
}

let style = {
  headline: css({
    color: "red",
    h1: {
      color: "blue",
      "&:hover": {
        color: "green"
      }
    },
    "@media screen and (min-width: 400px)": {
      h1: {
        fontSize: "50px"
      }
    }
  })
}

Is there no way to type-hint this?

If you use | operator instead of & it will work fine

type CSSDeclaration = {
    [P in keyof CSSStyleDeclaration]?: CSSStyleDeclaration[P];
} | NestedCSSDeclarations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM