Closed
Description
Bug Report
🔎 Search Terms
Partial keyof undefined
🕗 Version & Regression Information
I'm using 4.2.4 in production and it occurs. I have tested with 4.4 beta on the playground and it also occurs. I have no knowledge if the bug occurred in prior versions.
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about it.
⏯ Playground Link
Playground link with relevant code
💻 Code
type Data1 = {
test1: string
test2: string
}
type Data2 = {
test1: string
test2: boolean
}
let data1: Partial<Data1> = { };
let data2: Partial<Data2> = { };
// metadata.test = 'test';
let key = 'test1';
let value = 'test';
// Ok
data1[key as keyof Data1] = value;
// Error: Type 'string' is not assignable to type 'undefined'
// It seems like the bug occurs only if the object type has values of
// different types
data2[key as keyof Data2] = value;
// The real case scenario is I want to iterate some properties and
// assign them to the partial, so I expect that the partial has no
// initial properties defined at all and can be assigned any property of
// partialed type.
type TableData = {
id: string
title: string
icon: string
}
type Metadata = {
url: string
active: boolean
}
type CreateProps = Omit<TableData, 'id'> & Partial<Metadata>;
function create(props: CreateProps): void {
const id = 'test';
const tableData: TableData = {
id,
title: props.title,
icon: props.icon
}
const metadata: Partial<Metadata> = { };
for (const key of Object.keys(props)) {
// Build metadata from those props which are not tableData
if (typeof tableData[key as keyof TableData] === 'undefined') {
// Error:
// Type 'string | boolean' is not assignable to type 'undefined'
metadata[key as keyof Metadata] = props[key as keyof CreateProps]!;
}
}
}
🙁 Actual behavior
data2[key as keyof Data2]
is undefined
and it's not possible to assign anything to it.
🙂 Expected behavior
data2[key as keyof Data2]
should not be undefined
. At least it should be undefined | string | boolean
. It should also be possible to assign a value to it, despite being possible undefined
.