在一个文件中,我有我的类实现。

// 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}`);
  }
}

最佳答案

在流中,您可以导出类型

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

07-24 09:20