解构赋值中的 typescript 松散打字

标签 typescript types destructuring

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

相关文章:

使用嵌入插入的组件的 Angular 2+ 调用函数(ng-content)

json - Typescript 无法从 JSON 数据中读取 map<string,string>

javascript - 循环中的 ES6 解构和变量赋值

javascript - 解构 JavaScript 对象

angular - tslint : "Warning: The ' no-use-before-declare' rule requires type information"? 是什么意思

typescript - 如何使用 ionic2 的 braintree-web js 文件生成付款随机数

C++ 创建一个存储不同类型名称的 vector

sql - Postgres 中的代数数据类型

function - 错误 - 推断类型不够通用

javascript - 带 block 的常量声明