2

I would like to define a property on a TS class that will accept any string but not an empty string (''). Is there a way to do this?

Something like this:

class Foo {
   id: string & Not<''>
}

const bar = new Foo
bar.id = '' // ts compile error
bar.id = 'whatever string you want' // ts compile allowed

or

type nonEmptyString = Exclude<string, ''>
const something1: nonEmptyString = '' // ts compile error
const something: nonEmptyString = 'f' // ts compile allowed
const something2: nonEmptyString = '1' // ts compile allowed
3
  • That post has to do with passing an empty string into a function and doesn't have anything to do with classes. Commented Sep 28, 2021 at 17:22
  • 1
    Typescript does not have "not" types, sadly. You can use conditional types that can be used in functions (T extends '' ? never : T or something) . But I'm reasonably certain that its not possible to have the last three lines of your code work like you expect them to. Commented Sep 28, 2021 at 17:53
  • 2
    I really don't understand why they didn't allow this to work: type nonEmptyString = Exclude<string, ''> Commented Sep 29, 2021 at 19:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.