Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...