microsoft / microsoft/TypeScript
Spread operator in JSX causes loss of type information for inline functions defined outside the spread operator
还没有人认领这个 Issue。
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.4k
- 平均合并
- 1 天 19 小时
- 30 天内合并 PR
- 117
描述
Bug Report
When defining conditional types on a JSX component, using a spread operator causes loss of type information on inline functions while removing the spread operator resolves the issue.
🔎 Search Terms
- "jsx spread"
- "TS7006"
⏯ Playground Link
Playground link with relevant code
💻 Code
Given the following types and JSX:
/**
* Either all properties are included, or none of them should be
* @example
* type Ex = AllOrNone<{ search: string; onSearchChange: (value: string) => void}>
*
* // Ok
* const t1: Ex = {
* search: "hello",
* onSearchChange: (value) => console.log(value)
* }
*
* // Error, needs onSearchChange
* const t2: Ex = {
* search: "hello",
* }
*
* // Error, needs search
* const t3: Ex = {
* onSearchChange: (value) => console.log(value)
* }
*/
export type AllOrNone<T> = T | { [K in keyof T]?: never };
export type OrderHistoryTableProps = {
data: OrderRow[];
noDataText?: string;
} & SortParams &
FilterParams &
SearchParams;
type SortParams = AllOrNone<{
sorting: SortingState;
onSortChange: (state: SortingState) => void;
}>;
type FilterParams = AllOrNone<{
filter: ColumnFiltersState;
onFilterChange: (state: ColumnFiltersState) => void;
}>;
type SearchParams = AllOrNone<{
search: string;
onSearchChange: (value: string) => void;
}>;
function OrderHistoryTable({
data,
noDataText = "No orders to display!",
onFilterChange,
onSortChange,
sorting,
filter,
search,
onSearchChange,
}: OrderHistoryTableProps): JSX.Element {
...
}
/* sorting, filter, and search are correct types */
<OrderHistoryTable
data={rowData}
{...{ sorting, filter, search }}
onSortChange={onSortChange}
onFilterChange={setFilter}
onSearchChange={(value) => setSearch(value)} // TS7006: Parameter 'value' implicitly has an 'any' type.
/>
However, removing the spread operator resolves the issue:
<OrderHistoryTable
data={rowData}
sorting={sorting}
filter={filter}
search={search}
onSortChange={onSortChange}
onFilterChange={setFilter}
onSearchChange={(value) => setSearch(value)}
/>
🙁 Actual behavior
While using the spread operator for other props, the inline function loses type information.
🙂 Expected behavior
Given that the values provided in the spread operator are the correct type, the arguments in the inline function should retain type information.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从链接的 CodeSandbox 复现和 JSX 示例开始,重点关注其他 props 使用 spread operator 时内联 onSearchChange 函数的上下文类型推断。比较有无 spread 时的类型检查,然后添加一个回归测试,表明回调参数保留其预期类型。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- typescript
- 领域
- compilers
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 42/100