torch.validateDType
function validateDType(dtype: unknown): asserts dtype is DTypeRuntime validation that a value is a valid DType.
Checks if the provided value is a string and one of the supported data types.
Used for validating user input since JavaScript doesn't provide compile-time type guarantees.
This is a TypeScript assertion function that narrows the type to DType upon success.
Validation Rules:
- Must be a string (typeof check)
- Must be one of: 'float32', 'float16', 'int32', 'uint32', 'int8', 'uint8', 'bool'
- Case-sensitive: 'Float32' will fail
- Non-string values will fail with descriptive error
Use Cases:
- Validating dtype from JSON/external data
- User input parsing
- API boundary validation
- Type narrowing in conditional branches
When to Use:
- JavaScript/JSON sources where type safety is lost
- User-provided configuration
- API inputs from untrusted sources
- Optional: Already TypeScript-typed code doesn't need this
- Assertion function: Modifies type on success, throws on failure
- No return value: Returns void, used for side effects (type narrowing)
- Case-sensitive: Must exactly match 'float32', not 'Float32'
- Helpful errors: Error message lists all valid dtypes
- Throws on failure: Will throw Error if validation fails
- Non-string input: Any non-string value causes descriptive error
- No partial match: 'float' alone won't match 'float32'
Parameters
dtypeunknown- Untyped value to validate
Returns
asserts dtype is DType– void (assertion function - throws on failure)Examples
// Validate from JSON/user input
const userInput = JSON.parse(jsonString);
validateDType(userInput.dtype);
// If valid, now TypeScript knows userInput.dtype is DType
const tensor = torch.randn([3, 4], { dtype: userInput.dtype });
// Check before using in options
const options = { dtype: maybeString };
validateDType(options.dtype); // Throws if invalid
// Type narrowed - now safe to use
// Error message on failure
validateDType('InvalidType');
// Error: Invalid dtype: 'InvalidType'. Valid dtypes are: float32, float16, int32, uint32, int8, uint8, bool
// Type narrowing example
function createTensor(dtype: unknown) {
validateDType(dtype); // Asserts dtype is DType
// From here, TypeScript knows dtype is valid
return torch.zeros([10, 10], { dtype });
}
// Non-string types
validateDType(32); // Error: wrong type
validateDType(null); // Error: null is not a string
validateDType(['float32']); // Error: arrays not allowedSee Also
- [PyTorch N/A (torch.js runtime validation)](https://pytorch.org/docs/stable/generated/N/A .html)
- DType - The type being validated
- VALID_DTYPES - The Set of valid dtype strings
- DTypeInfo - Metadata for each dtype