【问题标题】:How do I make sure that my Lit element component props are properly typed in Typescript如何确保我的 Lit 元素组件道具在 Typescript 中正确输入
【发布时间】:2022-08-09 01:08:02
【问题描述】:

我有一个库,我想在其中为所有不同的框架创建一个按钮。所有这些组件 props 都应该具有来自 Typescript 接口的单一事实来源:

interface BaseButton {
    tiny: boolean;
    color: string;
}

如何确保根据该界面正确键入我的 Lit 元素属性?

@customElement(\"my-button\")
export class MyButton extends LitElement {
    @property({ type: Boolean })
    tiny = true;

    @property({ type: String })
    color = \"red\";
    ....
}
  • implements?我不确定你在问什么。是装修工吗?我认为您不能使这些取决于界面中的类型。
  • 因此,就像在 React 中一样,您可以执行以下操作:export const MyButton: FC<BaseButton> = ({ tiny, color, }) => { ... },如果您要添加不同的道具,构建将失败,我如何在这里实现相同的效果?

标签: typescript lit


【解决方案1】:

只需实现接口。

一般示例:

interface MyInterface {
  foo: boolean;
  bar: string;
}

// Invalid
class MyClass implements MyInterface {
  // TS2416
  foo: string;
  bar: boolean;
}

// Valid
class MyClass implements MyInterface {
  foo: boolean;
  bar: string;
}

你的代码:

export class MyButton extends LitElement implements BaseButton {...

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 1970-01-01
    • 2018-12-28
    • 2022-10-20
    • 2021-12-13
    • 2021-01-03
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    相关资源
    最近更新 更多