简体   繁体   中英

Converting Javascript member variable to Typescript member variable

I am trying to work out how to convert the member variables of my Javascript code to the Typescript equivalent.

In my Javascript code, after the constructor() I have:

this.theMediaItem = [];
this.theMediaItem.embedLink = '';
this.theMediaItem.username = '';

I have tried the following as the Typescript equivalent, inserted as required between the export class and the constructor() but it doesn't like the '.':

theMediaItem = [];
theMediaItem.embedLink = '';
theMediaItem.username = '';

For what you are describing, here's one typescript equivalent:

interface MediaItemArray<T> extends Array<T> {
    embedLink?: string;
    username?: string;
}

class MyClass {
    theMediaItem: MediaItemArray<any> = [];

    constructor() {
        this.theMediaItem.embedLink = "";
        this.theMediaItem.username = "";
    }
}

That's kind of strange though... you probably don't want to use an array and it's best to just have properties directly on the class:

class MediaItem {
    embedLink = "";
    username = "";
}

Or described in an interface:

interface MediaItem {
    embedLink: string;
    username: string;
}

Then, as you say in the comments, if you have a view you can add it as a property like so:

class MyView {
    mediaItem = new MediaItem()
}

Or if you are using an interface:

class MyView {
    mediaItem: MediaItem = {
        embedLink: "",
        username: ""
    };
}

You need to use syntax below, also make sure you don't define your theMediaItem as array, because from usage I see that you assign its properties:

class YourClass {
    constructor() {
       this.theMediaItem = {};
       this.theMediaItem.embedLink = '';
       this.theMediaItem.username = '';
    }
}

or do it in simple way:

class YourClass {
    theMediaItem = { embedLink: '', username: '' },    
    constructor() {
       // ...
    }
}

https://www.typescriptlang.org/docs/tutorial.html

Did you try the 'dictionary' pattern? Please refer the TS document and wiki page below.

interface Dictionary { [index: string]: string; }

https://typescript.codeplex.com/wikipage?title=Interfaces%20in%20TypeScript&referringTitle=TypeScript%20Documentation

https://en.wikipedia.org/wiki/Associative_array#Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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