A
A
Alexey Nikolaev2019-10-23 15:01:59
typescript
Alexey Nikolaev, 2019-10-23 15:01:59

Is it possible to do without type casting when assigning a string to a variable with a literal type?

Good day.
There is a type that describes a small object. By design, it should be a constant.

declare type KDFEncryptOptions = {
  kdf: 'scrypt',
  n: 8192,
};

However, when I type in a function argument with this type, I see the message "Type `string` is not assignable to type `scrypt`". I found a solution that involves casting a type when assigning. But it is not suitable due to one fundamental reason: in the project, ts is used only for design-time, only with type descriptions in declaration files. Marasmus? Yes. But somehow it has to be. How to be? Are there ways to declare a strict type with a string literal, and still allow strings (provided they match the literal)? Or maybe you can adjust the compiler to be more loyal to such cases? Thanks in advance.
somefunction(encryptOptions as KDFEncryptOptions);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2019-10-23
@Heian

try like this. we can give a ride

/**
 * @template {string} T
 * @param {T} encryptOptions
 */
function somefunction(encryptOptions)

it is equivalent in ts
however, if you pass an object, you will need to make a separate type with a generic purely for this function.

T
tosha4encko, 2019-10-23
@tosha4encko

So you need the encryptOptions type to be KDFEncryptOptions -

declare interface KDFEncryptOptions {
  kdf: 'scrypt';
  n: 8192;
}

function somefunction(encryptOptions: KDFEncryptOptions) {
  console.log('!!!');
}

let a: KDFEncryptOptions = { kdf: 'scrypt', n: 8192 };

somefunction(a);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question