簡體   English   中英

是否可以像在 Typescript 中那樣使用 class 屬性作為 Dart 中的類型?

[英]Is it possible to use class properties as types in Dart as it in Typescript?

在 Typescript

class Apple {
 constructor (public color: string, public size: number)
}

因此,可以通過這種方式使用上述 class 類型:

const growTo =(color: Apple['color'], size:Apple['size']) => console.log('growing..')

不是最好的例子,但重要的是它的含義。

In other words, in Typescript, it is possible to use class property type to point type somewhere in another class, function and it creates really easy readable code.

不幸的是,我在 Dart 中沒有找到任何關於如何做到這一點的提及。 問題 - 是否可以在 Dart 中做類似的事情?

更新 1 - 目的示例:

首先,我必須為我的英語道歉,它不是我的母語。

目標:我們有任務列表,我們想將它們轉換為 Map。

Dart 實現將如下所示:

class Task{
  int id;
  String name;
  Task({this.id,this.name});
}


void main() {

  List<Task> tasks = [Task(id: 0, name: 'todo1'), Task(id:1, name: 'todo2')];
  Map<int, Task> tasksMap = { for (Task task in tasks) task.id: task };
  
}

問題 1. 什么值用作 Map 的鍵? 這是一個 id,但是,要知道它,我們需要查找 map 將如何填充的方法。

問題 2. 如果有一天我們決定將任務 class 中的 id 類型從 int 更改為 String 怎么辦? 在這種情況下,我們將需要更改發生的任何類型錯誤,其中我們使用類型 int 作為 id 類型。

如何用 Typescript 解決:

class Task{
    constructor(public id: number, public name: string){};
}
    
const tasks: Task[] = [new Task(0,'todo1'), new Task(1, 'todo2')]
const tasksMap: Map<Task['id'], Task> = new Map(tasks.map(task=> [task.id, task]))
  

解釋:

Task['id'] 指的是 class 任務中的當前類型,現在是數字。 如果我們將 class 中的類型更改為字符串,那么 Map 鍵將自動跟隨更改並且也將是字符串。

問題 1 - 已解決。 我們總是知道我們用什么來做鑰匙。

問題 2 - 已解決。 如果我們更改 Task.id 的類型,那么所有類型都將更改。

不。

Dart 不允許您以任何其他方式引用類型:

  • 文字類型( intList<String>int Function(int)
  • 類型變量 ( T )
  • 一個 typedef 名稱( F其中typedef F = some Function(type);

從 Dart 2.13 開始,有一個解決方案可以使用 typedefs 解決這個問題:

typedef AppleColor = String;
    
class Apple {
  final AppleColor color;
  const Apple ({required this.color});
}
    
void growTo(AppleColor color) => print('growing $color..');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM