如何在另一个文件中使用类类型?

时间:2017-09-21 12:35:07

标签: javascript flowtype

在一个文件中,我有我的班级实现..

// person.js
class Person {
    ...
}

另一个文件中,我想使用此类型...

// job.js
class Job {
  person: Person; // ERROR: Flow: identifier `Person`. Could not resolve name

https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAodxhgA4FMBOAznAHYB0AVoagC4CeeYACgcSQPLY0CWphYAXjABvVGDCEaAQxoBXQgC4JNfNxIBzVAF90AYxhTC-FkVIixYElIC2uJZNUaA3BbhdeJRc1alOPPi7iunwqsro0cPhgABRWtvYqauoANGBu-lYwfh5eJmzZfACU5uLiNAAW3IRkcbiClja4gaUVVWTpOfUdpFJZ7gEWOhbquDQAytJyhNHFoqVgwZ5wMLhk8OrRAAYAJMKt1bVaYFVgu-vt-Z5kkjLyWpuFzTpDqJhgAJIAcmAAgp-sABUABIAUQASmAAGLvAAyIIwWAocAARpRqPpDPwAFIokpgHg0FYJRzqZp4UwkJR5UhOMBvcFg9hgpSQ+AIJTcAAmuBIPCg3AIYE21JImzIYAAwnBZDBOZY4DQwPhcMQYAA3Oq1CyLBxhCJRaIEonKEmpclsKk+EizCxlSrVI11ISO5p2trmsxCD0kJ7ocQjcaTeQzPFBPjLVbrLZne1kb01RpHBCRADWYAQ3Aqpz2scd90eg206CAA

/* @flow */

// person.js
type PersonOptions = {
  status: string
}

class Person {
  name: string;
  options: PersonOptions;
  constructor (name: string, optionalOptions: PersonOptions) {
    this.name = name;
    this.options = optionalOptions;
  }

  getStatus() {
    console.log(`${this.name} is ${this.options.status}`);
  }
}


// IN ANOTHER FILE

// job.js
class Job {
  title: string;
  person: Person; // ERROR: Flow: identifier `Person`. Could not resolve name
  constructor (title: string, person: Person) {
    this.title = title;
    this.person = person;
  }

  getStatus() {
    console.log(`${this.person.name} work with ${this.title}`);
  }
}

2 个答案:

答案 0 :(得分:2)

// in person.js
export default class Person {
   //...
}
//in other file
import Person from './person.js';
class job {
   person: new Person()
}

答案 1 :(得分:1)

在流程中,您可以导出类型

export type Person = {
  // ...
}

并将其导入另一个文件

import type { Person } from './Person'

如果您的班级有默认导出,您可以简单地:

// Person.js

export default class Person {
   //...
}

// another file

import type Person from './Person'

class Job {
  title: string;
  person: Person; // Flow should not throw an error      
  constructor (title: string, person: Person) {
    this.title = title;
    this.person = person;
  }

  getStatus() {
    console.log(`${this.person.name} work with ${this.title}`);
  }
}

查看DOCUMENTATION