패키지, 저장소 및 앱 카테고리 검색

패키지 상세v2.1.1

type_plus

당신의 타입에 슈퍼파워를 부여하고 제네릭을 더욱 풍성하게 만들어보세요. 타입을 다시 위대하게 만드세요.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
51만
좋아요
30
Pub 점수
150

패키지 설치

flutter pub add type_plus

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

TypePlus는 제네릭을 다루는 데 유용한 강력한 확장과 유틸리티를 통해 Dart의 타입 시스템을 향상시킵니다. 복잡한 타입을 더 직관적이고 표현력 있게 다룰 수 있도록 문법적 당근과 유틸리티 메서드를 제공합니다. 핵심 Dart 타입을 확장함으로써 타입 단언, null 안전 패턴, 제네릭 변환과 같은 일반적인 작업을 간소화합니다. Flutter 또는 Dart 애플리케이션에서 고급 타입 시나리오를 관리할 때 더 깔끔하고 가독성이 좋은 코드를 원하는 개발자에게 이상적입니다.

사용 사례

  • 복잡한 제네릭 작업 간소화
  • 널 안전 워크플로 강화
  • 타입이 많은 코드의 가독성 향상
  • 타입 암시의 단순화
  • 재사용 가능한 유형 유틸리티 작성
  • 일반 함수에서 반복 코드 줄이기

주요 기능

  • 유용한 메서드를 제공하는 핵심 Dart 유형을 확장합니다
  • 향상된 일반 처리를 제공
  • 널 안전성 향상 지원
  • 타입 조작을 위한 간결한 구문 제공
  • 유형 인스펙션을 위한 유틸리티 함수를 포함합니다
  • 모든 Dart 플랫폼에서 원활하게 작동합니다

적합한 대상

  • 고급 제네릭을 사용하는 Dart 개발자
  • 유형 관련 반복 코드를 줄이려는 팀
  • 표현적인 유형 처리가 필요한 프로젝트
  • 코드의 명확성과 유지보수에 중점을 둔 개발자
  • 복잡한 상태 또는 데이터 모델을 가진 플러터 앱

고려 사항

  • 초보자들의 학습 곡선을 증가시킬 수 있음
  • 대규모 코드베이스에서 사용할 때는 신중한 검토가 필요합니다
  • 적절한 타입 설계의 대체물이 아님
  • 기본 예제 외에 문서가 제한적
  • 고급 제네릭을 이미 사용하는 프로젝트에 가장 적합

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Type Plus

Give your types superpowers and spice up your generics. Make types great again.

type_plus is a utility package to bring some advanced capabilities to type variables and generic type arguments With type_plus you can easily deconstruct any type variable or generic type argument.

Getting started

First you have to register all types you want to use later on. It makes sense to do this early on in the main() method of your dart program.

You only need to register custom types. All primitive and default dart types (String, int, ..., List, Map, ...) are already registered by default.

For basic, non-generic types you can do the following:

TypePlus.add<MyClass>();

For generic types, you have to specify a type factory. This is a special kind of function with the following syntax:

class MyClass<A, B> {}

void main() {
  TypePlus.addFactory(<A, B>(f) => f<MyClass<A, B>>());
}

As you can see, the type factory function is a generic function that takes as many type arguments (A, B) as your target class defines. Then you have to call f with your generic type.

After that, whenever you have a generic type argument or type variable, you can use the following properties on it:

void myGenericFunction<T>() {
  String name = T.name; // the full name of the type
  String id = T.id; // a unique id of the type
    
  Type base = T.base; // the base type of a generic type
  List<Type> args = T.args; // the type arguments of a generic type
}

Read on for a more detailed explanation of the available properties or take a look at the example.

Working with types

There are two ways you can get an instance of a Type in dart:

  1. Generic type argument
    This can either come from a generic class or generic function.

    class MyClass<T> {
      String get name => T.name;
    }
    // or
    void myFunction<T>() {
      String name = T.name;
    }
    
  2. Type variable
    Types can also be used as variables.

    Prior to Dart 2.15 when using generic types you have to use the typeOf<T>() helper function

    void main() {
      Type a = int;
      Type b = List<int>; // for dart < 2.15 instead do typeOf<List<int>>()
      
      String aName = a.name;
      String bName = b.name;
    
      // or use in expressions wrapped in ()
      print((MyClass<String>).name);
    }
    

Type decomposition

With this package, you can decompose a generic type into its type components. Let's say we have the type Map<String, int>, then:

  • the decomposed base type would be Map (or more concrete Map<dynamic, dynamic> because of how darts type system works) and
  • the decomposed type arguments would be String and int.
void main() {
  var type = Map<String, int>;
  
  String name = T.name; // = "Map<String, int>"
  
  Type base = T.base; // = Map
  List<Type> args = T.args; // = [String, int]
}

Generic invocation

Normally in dart, a generic type argument can only be provided statically. This means you cannot invoke a generic method when you only have a type variable.

With this package however, you can call a generic method and provide type variables for the generic arguments:

void printType<T>() {
  print(T.name);
}

void main() {
  var type = typeOf<Map<String, int>>();
  
  // prints: "Map<String, int>"
  printType.callWith(typeArguments: [type]);
  
  // prints: "String"
  printType.callWith(typeArguments: [type.args.first]);
}

Type IDs

With type_plus, every type has a unique id.

Additionally to identifying a type, you can use ids to construct a generic type from a string:

void main() {
  Type a = List;
  Type b = int;
  
  Type newType = TypePlus.fromId('${a.id}<${b.id}>');
  assert(newType.base == a);
  assert(newType.args.first == b);
}

When registering a type, you can provide a custom id to be used:

void main() {
  TypePlus.add<MyClass>(id: 'CoolId');
  
  Type myType = TypePlus.fromId('CoolId');
  assert(myType == MyClass);
}

Type inheritance

When dealing with object variables, there exists the is operator for checking the inheritance of an object. However there exists nothing like this for types.

With type_plus, you can do

  • typeA.implements(typeB) and
  • typeB.implementedBy(typeA)

to check the inheritance of types.

In order for this to work, you have to explicitly set the supertypes of any type when registering it. This includes any extends, implements and mixins.

class MyClass extends List<int> {}

void main() {
  var listType = List<int>;
  
  TypePlus.add<MyClass>(superTypes: [listType]);
  
  var myType = MyClass;
  
  assert(myType.implements(listType));
  assert(listType.implementedBy(myType));
  
  assert(!myType.implements(List)); // needs to be the full specified type
} 

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.