Home > Back-end >  How do I reference the value of a prop in a typescript conditional?
How do I reference the value of a prop in a typescript conditional?

Time:06-02

I'm trying to create a type validator and I'm not 100% sure if what I'm trying to do is possible.

Basically, wondering if it's possible to infer a types own value so that I can use it in a conditional.

type Validate = OwnValue extends `${string} ${string}` // How do I reference its own value?
  ? 'I have whitespace'
  : 'I dont have whitespace'

type Props = {
  prop?: Validate;
}

const Component = (props: Props) => <div {...props} />;

CodePudding user response:

You cannot access value to define Typescript type, as there are no typescript enhancements after compilation and values can be determined in runtime only (maybe beside the cases where you create consts like const s = 'stringValue'. Typescript code is converted to pure JS without any typing.

CodePudding user response:

Got it working. Turns out I needed a lesson in generics!

type Validate<S extends string> = S extends `${string} ${string}`
  ? 'I have whitespace'
  : S

type Props<S extends string> = {
  prop?: Validate<S>;
}

function Component<S extends string>(props: Props<S>) {
  return <div {...props} />;
};

const Test = () => {
  return (
    <>
      <Component prop="nowhitespace" />  // valid
      <Component prop="white space" />   // not valid
    </>
  )
}
  • Related