简体   繁体   中英

Typescript Create Generic Object

I'm trying to create an object in typescript. I want to do this generically so that it automatically gets it's default based off of its type

interface IModal {
    content: string;
    count: number
 }

Normally I would declare an Instance of it like so:

var modal: IModal = {
    content: '',
    count: 0
};

I don't want to have to do this everytime. I want to do this so that the it automatically create an instance of the interface with Typed default ie

number = 0,
string = '',
boolean = false,
MyCustom = new MyCustom

I want to do something like this:

export class MakeObject {

     Make<T> : T = function(iInterface) => {
        return default(T);
     }     
}

But I don't think that will work

I want to do this so that the it automatically create an instance of the interface with Typed default ie

You can't do this magically as interfaces do not exist at runtime. That said you can write code to do this quite easily:

interface Model {
    content: string;
    count: number
}

function createModel({
    // Add defaults
    content = '',
    count = 0
} = {}): Model {
    return { content, count }
}

createModel(); // Okay
createModel({ count: 1 }); // Okay
createModel({ counted: 1 }); // Error: Typo

Interfaces can extends classes, so you can make it like this:

class DefaultModel {
    content = ''
    count = 0
}

export interface IModel extends DefaultModel {}
/* since interface generates no code,
 * you can also export the default instance using the same name, if you like
 */
export const IModel: IModel = new DefaultModel
// or export the default class, if you're more interested in it
export const IModel = DefaultModel

another way to do it, if you are not against classes, is using abstract classes, in typescript they are as flexible as interfaces (eg: interchangeable with type ) and exist at runtime:

abstract class BaseModel {
    content = ''
    count = 0
}

const modal = new (class extends BaseModel {})

Note that with this approach content and count are not abstract , so while you can still use BaseModel for typecheck, if you need to force subclasses to provide their own values, you may still create an interface to clear the default:

class SomeModel extends BaseModel {} // OK    

interface IModel extends BaseModel {}

class SomeModel implements IModel {} // NOT OK: Property 'content' is missing

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