Typescript free input in destructuring assignment

When using destructuring assignment and variable, because the Typescript property name seems to be losing types.

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`
};
Run codeHide result
+4
source share
2 answers

I don't think this is typescript error, there are some problems with this code

const {[name]: value} = o ;

what kind of string is it, you define a constant without a name, and then use something like type and assign o

And what is it value?

Since I don’t know what your idea was, I can offer these codes:

If you want to consider it as a type

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

If you want to use it as a value

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

Edit:

, , , typescript, , . .

, .

:

, , string , , __proto__ constructor, string.

, , :

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

, . , string.

0

Source: https://habr.com/ru/post/1691451/


All Articles