简体   繁体   English

打字稿中的打字稿松散打字

[英]Typescript loose typing in destructuring assignment

When using destructuring assignment and variable as property name Typescript seems like loses types. 当使用解构赋值和变量作为属性名时,Typescript似乎失去了类型。

 interface O { [val: string]: string; } const o: O = { foo: '' }; const f = (name: string) => { const {[name]: value} = o; // now `value` has type any, how to make it type `string`? const value1 = o[name] || ''; // and `value1` has correct type `string` }; 

I don't think it's typescript a bug, there are some issues on this code 我不认为它是打字稿是一个错误,这个代码有一些问题

const {[name]: value} = o ;

what is this line, you are defining a const with no name, then using something like type and assigning o 这一行是什么,你定义一个没有名字的const,然后使用类似的东西和分配o

Also what is value ? 还有什么value

Since I don't know what was your idea I can suggest these codes: 由于我不知道你的想法是什么,我可以建议这些代码:

If you want to consider it as type 如果你想把它当作类型

const x : {[name:string]:string} = o;

If you want to use it as value 如果要将其用作值

const x = {[name] : 'my value'};

Edit: 编辑:

After thinking it some more, its obvious that both cases should return the same result, and typescript probably doesn't considered the possible prototype of the object. 在考虑了一些之后,很明显两种情况都应该返回相同的结果,而typescript可能不会考虑对象的可能原型。 so it should return string type. 所以它应该返回字符串类型。

And you must protect the two cases of missing entries and possible non string prototype access. 并且您必须保护两个缺少条目和可能的非字符串原型访问的情况。

Original: 原版的:

The value given to the destructuring is a string , and can be any string , including things like __proto__ or constructor that will result in a non string type. 给予解构的值是一个string ,可以是任何字符串 ,包括__proto__constructor类的东西,它们将导致非string类型。

If you know the optional keys that you might have, then this will work: 如果你知道你可能有的可选键,那么这将有效:

const f = (name: keyof typeof o) => {
    const {[name]: value} = o;
    // now `value` has type string
};

I think the bug is in the latter example without destructuring. 我认为这个bug在后一个例子中没有解构。 By passing certain strings you might get a non string value. 通过传递某些字符串,您可能会获得非string值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM