What I wanna do is so simple.
In the example below,
interface InterfaceA { a: string, b: number }
interface InterfaceB { c: keyof InterfaceA }
const testMethod = (test: InterfaceB) => {
const TestObject: InterfaceA = { a: '', b: 1 }
TestObject[test.c] =
}
causes 'Type 'any' is not assignable to type 'never'' error.
I thought that test.c can be assigned in TestObject since c is the key of Interface A.
How can I make things work?
You are receiving this error because the type of
test.ccan not be narrowed down any more thankeyof InterfaceA. In other words, if we try to assign toTestObject[test.c]typescript wont be able to determine if we need to assign astringor anumber. So it determines that the type must be all valid types at the same time, in this casenumber & string. However no value can be both anumberand astringat the same time, so the resulting type ends up beingnever(See this playground for an example).We can solve this by helping typescript narrow down the actual type of
test.clike this:playground