Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

TypeScript error trying to set a valid object property (key is treated as string despite conditional check)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...