Menu

1 / 2

Dart Extension Types — Zero-cost Type-safe Wrappers

DEV Community·kanta13jp1·6 months ago
#I0sySFNJ
#dart#flutter#webdev#indiedev#string
Reading 0:00
15s threshold

Dart Extension Types — Zero-cost Type-safe Wrappers

Introduced in Dart 3.3, Extension Types let you treat an existing type as a distinct type at compile time — with zero runtime overhead. They're the "newtype" pattern Dart developers have wanted for years.

Basic Syntax

// Before: String IDs are easy to confuse String userId = 'abc-123' ; String orgId = 'org-456' ; // Passing orgId where userId is expected compiles fine ❌

// After: distinct types at compile time extension type UserId ( String value ) implements String {} extension type OrgId ( String value ) implements String {}

UserId userId = UserId ( 'abc-123' ); OrgId orgId = OrgId ( 'org-456' );

void fetchUser ( UserId id ) { ... } fetchUser ( orgId ); // ❌ Compile error: OrgId is not UserId

Enter fullscreen mode

Exit fullscreen mode

implements vs. No implements

// With implements String: all String methods are available extension type UserId ( String value ) implements String {}

final id = UserId ( 'abc-123' ); id . length ; // ✅ id .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.