简体   繁体   English

Typescript中的递归类型声明

[英]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. 我要的是这种类型的接受局部性质CSSStyleDeclaration ,而且,对于任何属性匹配的属性CSSStyleDeclaration ,我想它映射回类型本身。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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