我可以“分解”一个功能组件的道具的类型吗?
这段代码编译得很好。
type DataType = {
a: string;
b: string;
};
const ShowA = ({ a }: DataType) => <p>{a}</p>;但是,这不会:
const Component = () => {
const data = { a: "foo", b: "bar" };
<ShowA a={data.a} />;
};这会导致错误Property 'b' is missing in type '{ a: string; }' but required in type 'DataType'.。
我理解这个错误,但是有没有语法可以让我这样做呢?b将始终存在于检索到的数据中,所以将其标记为可选的b?: string感觉是错误的。我希望有一行代码可以替代它:
const ShowA = (props: DataType) => {
const { a } = props;
return <p>{a}</p>;
}发布于 2021-08-05 07:51:49
Typescript有一个实用程序类型就可以做到这一点:Pick
type DataType = {
a: string;
b: string;
};
type OnlyAType = Pick<DataType, "a"> // { a: string }
const ShowA = ({ a }: Pick<DataType, "a">) => <p>{a}</p>;https://stackoverflow.com/questions/68662449
复制相似问题