【发布时间】:2020-01-25 07:03:06
【问题描述】:
我目前正在将 JavaScript 代码库重写为 Typescript。我发现函数中的数据定义如下 MyProps:
interface MyProps {
type: string;
foo?: unknown;
bar?: unknown;
someCommonProps: unknown;
}
用法一直是这样的:
const myFunction = (props: MyProps) => {
const { type, foo, bar, someCommonProps } = props;
if (foo) {
//Do something
}
if (bar) {
//Do something else
}
};
通过进一步调查,我发现接口/类型可以像这样更精确地定义:
interface Foo {
type: "a" | "b" | "c";
foo: unknown;
}
interface Bar {
type: "d" | "e" | "f";
bar: unknown;
}
type FooBar = Foo|Bar;
type MyProps = FooBar & {
someCommonProps: unknown;
}
但是通过将新的 MyProps 分配给 props,我会在 myFunction 的第一行得到一个错误:Property 'foo' does not exist on type 'MyProps'。与“酒吧”类似。在不以可能引入错误的方式重写的情况下处理此问题的最佳方法是什么?
【问题讨论】:
标签: typescript