Typescript and model class definition


#1

Hi,

I’m using typescript with ember and want to check if a passed param is a model record instead of using any , something like this:

import Ember from 'ember';
import { action } from '@ember-decorators/object';

const {
  Controller
} = Ember;

// i tried this but ts will tell me that i have to add `destroyRecord` also:
// `app/controllers/libraries/index.ts(21,15): error TS2339: Property 'destroyRecord' does not exist on type 'Library'.`
// i want to have something that contains the model defintion to extend from it :)
type Library = {
  name: string,
  address: string,
  phone: string,
  // i don't like to do something like this
  destroyRecord: any,
  save: any,
  anotherUsedMethod: any
}

export default class LibrariesIndexController extends Controller {

  @action
  // i don't want to use `any` here
  // i want to do something like this `library: Library`
  deleteLibrary(library: Library) {
    let confirmation = confirm("Are you sure ?");

    if (confirmation) {
      library.destroyRecord();
    }
  }
}

#2

destroyRecord is a legitimate part of what makes a model a model. It really is part of the type. There’s no reason to say it’s any, you can say it’s a function. In your example it would be enough to say destroyRecord: () => void.

But really you probably want to install @types/ember-data, which includes a more complete definition of destroyRecord.


#3

hi @ef4, thanks for your reply but i think that you didn’t understand what i want to do :frowning:

If i don’t add any after the passed param like this deleteLibrary(library: any) { ... }, typescript(on the console/terminal) will print an error !

I’m using typescript to have a strict checking of my passed params, so here i want the library passed param to be checked against a model record that has my model attributes(name, address, phone …), methods(save, destroyRecord, serialize, toJson …), properties(isDeleted, isEmpty …) https://www.emberjs.com/api/ember-data/release/classes/DS.Model , something like this:

import ModelRecord from 'some-where';

// ...
deleteLibrary(library: ModelRecord) {
  // ...
}

I tried this:

import DS from 'ember-data';

// ...
deleteLibrary(library: DS.Model) {
  // ...
}

It work’s but i don’t really know if this is the correct solution :frowning:


#4

If your model is written in Typescript, then you can just do what you showed in the first example.

// app/models/library.ts
import DS from 'ember-data';
import { attr } from '@ember-decorators/data';

export default class extends DS.Model {
  @attr('string') name;
}
// app/controllers/something.js
import Library from '../models/library';

// ...
deleteLibrary(library: Library) {
  library.destroyRecord();
}