The code below shows TS error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'myObj'. No index signature with a parameter of type 'string' was found on type 'myObj'.ts(7053)
I understand why the first approach fails, but why won't the 2nd work when the conditional is expressly checking that the keyName variable is a valid key on this object?
declare type myObj = {
subObj: {
prop1?: boolean;
prop2?: boolean;
};
};
const x: myObj = { subObj: { prop1: true } };
let keyName = 'prop2';
x.subObj[keyName] = false; //TS error here makes sense because keyName is of type string and may not be a valid key
if (keyName in x.subObj) x.subObj[keyName] = false; // The conditional guarantees the key exists here. Why does this fail?
Note: I don't believe I can use "typeof" here because I'm trying to access properties of a child object, and I'd rather not create interfaces for each sub-object.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…