Skip to content

User-defined type guards with ternary operator  #30864

@k8w

Description

@k8w

Search Terms

type guards ternary

Suggestion

Support to use dser-defined type guards with ternary operator

Use Cases

More complex type guards function

Examples

function checkAnimal(animal: Animal)
  : animal is Cat ? 'Cat'
    : animal is Dog ? 'Dog'
    : animal is Animal
{
  // ...
}

let value: any;
let checkResult = checkAnimal(animal);

if(checkResult === 'Cat'){
  // value is Cat now
}
else if(checkResult === 'Dog'){
  // value is Dog now
}
else if(checkResult){
  // value is other Animal
}
else{
  // value is not Animal
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions