gpt4 book ai didi

解构赋值中的 typescript 松散打字

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:45 26 4
gpt4 key购买 nike

当使用解构赋值和变量作为属性名称时,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`
};

最佳答案

我不认为这是 typescript 的错误,这段代码存在一些问题

const {[name]: value} = o ;

这一行是什么,你在定义一个没有名字的常量,然后使用类型之类的东西并赋值 o

还有什么是value

因为我不知道你的想法是什么,我可以建议这些代码:

如果你想把它当作类型

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

如果你想用它作为值

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

关于解构赋值中的 typescript 松散打字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com