user3612643
user3612643

Reputation: 5792

Enforce suffix in typed string literals

Consider the following types:

type Extent = number | /.*px/ | /.*pt/;

interface Size {
  width: Extent;
  height: Extent;
}

Of course that's not legal TypeScript, but my intention is to enforce some suffixes in string literal types. I guess that's not possible at all, but does someone know an elegant solution?

EDIT:

Looks like that might be possible in TypeScript 4.1.0. I just saw: https://github.com/microsoft/TypeScript/pull/40336

So, I tried with the nightly playground:

type Extent<T extends number> = number | `${T}px` | `${T}pt`;

const ex1 : Extent<number> = 42;
const ex2 : Extent<number> = '42px';
const ex3 : Extent<number> = '42uu'; // <-- should fail!

But the line with ex3 didn't fail...

Playground link

Upvotes: 2

Views: 537

Answers (1)

user3612643
user3612643

Reputation: 5792

The issue has been fixed by this pull request.

That can be verified in this playground example:

type Size = `${number}px`;

interface Foo {
    size: Size;
}

function foo(_sz: Size) {}

const ok : Foo  = {size: "42px" };
foo("42px");

const fails : Foo = {size: "42"};  // FAILS as expected
foo("42");                         // FAILS as expected

Upvotes: 1

Related Questions